file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@unification-com/xfund-router/contracts/lib/ConsumerBase.sol";
import "./interfaces/ILandRegistry.sol";
import "./LandAuction.sol";
contract LandAuctionV3 is ConsumerBase, Ownable, ReentrancyGuard {
uint32 constant clearLow = 0xffff0000;
uint32 constant clearHigh = 0x0000ffff;
uint32 constant factor = 0x10000;
int16 public constant xLow = -96;
int16 public constant yLow = -99;
int16 public constant xHigh = 96;
int16 public constant yHigh = 99;
enum Stage {
Default,
Inactive1,
Inactive2,
PublicSale
}
uint256 public ethToShib;
bool public multiMintEnabled;
LandAuction public auctionV1;
LandAuction public auctionV2;
ILandRegistry public landRegistry;
IERC20 public immutable SHIB;
Stage public currentStage;
mapping(address => uint32[]) private _allMintsOf;
event StageSet(uint256 stage);
event multiMintToggled(bool newValue);
event LandBoughtWithShib(
address indexed user,
uint32 indexed encXY,
int16 x,
int16 y,
uint256 price,
uint256 time,
Stage saleStage
);
constructor(
IERC20 _shib,
LandAuction _auctionV1,
LandAuction _auctionV2,
ILandRegistry _landRegistry,
address _router,
address _xfund
) ConsumerBase(_router, _xfund) {
SHIB = _shib;
auctionV1 = _auctionV1;
auctionV2 = _auctionV2;
landRegistry = _landRegistry;
}
modifier onlyValid(int16 x, int16 y) {
require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE");
require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE");
_;
}
modifier onlyStage(Stage s) {
require(currentStage == s, "ERR_THIS_STAGE_NOT_LIVE_YET");
_;
}
function bidInfoOf(address user)
external
view
returns (int16[] memory, int16[] memory)
{
(int16[] memory xsV1, int16[] memory ysV1) = auctionV2.bidInfoOf(user);
uint256 lengthV1 = xsV1.length;
uint256 bidCount = _allMintsOf[user].length;
int16[] memory xs = new int16[](bidCount + lengthV1);
int16[] memory ys = new int16[](bidCount + lengthV1);
for (uint256 i = 0; i < lengthV1; i = _uncheckedInc(i)) {
xs[i] = xsV1[i];
ys[i] = ysV1[i];
}
uint256 ptr = lengthV1;
uint32[] storage allMints = _allMintsOf[user];
uint256 length = allMints.length;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
(int16 x, int16 y) = _decodeXY(allMints[i]);
xs[ptr] = x;
ys[ptr] = y;
ptr = _uncheckedInc(ptr);
}
return (xs, ys);
}
function getReservePriceShib(int16 x, int16 y)
public
view
onlyValid(x, y)
returns (uint256)
{
// this will revert if not up for sale
uint256 reservePrice = auctionV1.getReservePrice(x, y);
// to check if this was bid on, in the bidding stage
(uint256 cAmount, ) = auctionV1.getCurrentBid(x, y);
require(cAmount == 0, "ERR_ALREADY_BOUGHT");
uint256 reservePriceInShib = (ethToShib * reservePrice) / 1 ether;
require(reservePriceInShib > 0, "ERR_BAD_PRICE");
return reservePriceInShib;
}
function mintPublicWithShib(int16 x, int16 y)
external
onlyStage(Stage.PublicSale)
nonReentrant
{
// this will revert if not up for sale
uint256 reservePriceInShib = getReservePriceShib(x, y);
address user = msg.sender;
SHIB.transferFrom(user, address(this), reservePriceInShib);
uint32 encXY = _encodeXY(x, y);
_allMintsOf[user].push(encXY);
landRegistry.mint(user, x, y);
emit LandBoughtWithShib(
user,
encXY,
x,
y,
reservePriceInShib,
block.timestamp,
Stage.PublicSale
);
}
function mintPublicWithShibMulti(
int16[] calldata xs,
int16[] calldata ys,
uint256[] calldata prices
) external onlyStage(Stage.PublicSale) nonReentrant {
require(multiMintEnabled, "ERR_MULTI_BID_DISABLED");
uint256 length = xs.length;
require(length != 0, "ERR_NO_INPUT");
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH");
uint256 total;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
total += prices[i];
}
address user = msg.sender;
SHIB.transferFrom(user, address(this), total);
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
uint256 reservePriceInShib = getReservePriceShib(x, y);
require(
reservePriceInShib == prices[i],
"ERR_INSUFFICIENT_SHIB_SENT"
);
uint32 encXY = _encodeXY(x, y);
_allMintsOf[user].push(encXY);
landRegistry.mint(user, x, y);
emit LandBoughtWithShib(
user,
encXY,
x,
y,
prices[i],
block.timestamp,
Stage.PublicSale
);
}
}
function setStage(uint256 stage) external onlyOwner {
currentStage = Stage(stage);
emit StageSet(stage);
}
function setLandRegistry(address _landRegistry) external onlyOwner {
landRegistry = ILandRegistry(_landRegistry);
}
function setAuctionV1(LandAuction _auctionV1) external onlyOwner {
auctionV1 = _auctionV1;
}
function setAuctionV2(LandAuction _auctionV2) external onlyOwner {
auctionV2 = _auctionV2;
}
function setMultiMint(bool desiredValue) external onlyOwner {
require(multiMintEnabled != desiredValue, "ERR_ALREADY_DESIRED_VALUE");
multiMintEnabled = desiredValue;
emit multiMintToggled(desiredValue);
}
function increaseRouterAllowance(uint256 _amount) external onlyOwner {
require(_increaseRouterAllowance(_amount), "ERR_FAILED_TO_INCREASE");
}
function getData(address _provider, uint256 _fee)
external
onlyOwner
returns (bytes32)
{
bytes32 data = 0x4554482e534849422e50522e4156430000000000000000000000000000000000; // ETH.SHIB.PR.AVC
return _requestData(_provider, _fee, data);
}
function withdrawShib(address to, uint256 amount) external onlyOwner {
SHIB.transfer(to, amount);
}
function withdrawAny(
address token,
address to,
uint256 amount
) external onlyOwner {
IERC20(token).transfer(to, amount);
}
function receiveData(uint256 _price, bytes32) internal override {
ethToShib = _price;
}
function _uncheckedInc(uint256 i) internal pure returns (uint256) {
unchecked {
return i + 1;
}
}
function _encodeXY(int16 x, int16 y) internal pure returns (uint32) {
return
((uint32(uint16(x)) * factor) & clearLow) |
(uint32(uint16(y)) & clearHigh);
}
function _decodeXY(uint32 value) internal pure returns (int16 x, int16 y) {
x = _expandNegative16BitCast((value & clearLow) >> 16);
y = _expandNegative16BitCast(value & clearHigh);
}
function _expandNegative16BitCast(uint32 value)
internal
pure
returns (int16)
{
if (value & (1 << 15) != 0) {
return int16(int32(value | clearLow));
}
return int16(int32(value));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../vendor/OOOSafeMath.sol";
import "../interfaces/IERC20_Ex.sol";
import "../interfaces/IRouter.sol";
import "./RequestIdBase.sol";
/**
* @title ConsumerBase smart contract
*
* @dev This contract can be imported by any smart contract wishing to include
* off-chain data or data from a different network within it.
*
* The consumer initiates a data request by forwarding the request to the Router
* smart contract, from where the data provider(s) pick up and process the
* data request, and forward it back to the specified callback function.
*
*/
abstract contract ConsumerBase is RequestIdBase {
using OOOSafeMath for uint256;
/*
* STATE VARIABLES
*/
// nonces for generating requestIds. Must be in sync with the
// nonces defined in Router.sol.
mapping(address => uint256) private nonces;
IERC20_Ex internal immutable xFUND;
IRouter internal router;
/*
* WRITE FUNCTIONS
*/
/**
* @dev Contract constructor. Accepts the address for the router smart contract,
* and a token allowance for the Router to spend on the consumer's behalf (to pay fees).
*
* The Consumer contract should have enough tokens allocated to it to pay fees
* and the Router should be able to use the Tokens to forward fees.
*
* @param _router address of the deployed Router smart contract
* @param _xfund address of the deployed xFUND smart contract
*/
constructor(address _router, address _xfund) {
require(_router != address(0), "router cannot be the zero address");
require(_xfund != address(0), "xfund cannot be the zero address");
router = IRouter(_router);
xFUND = IERC20_Ex(_xfund);
}
/**
* @notice _setRouter is a helper function to allow changing the router contract address
* Allows updating the router address. Future proofing for potential Router upgrades
* NOTE: it is advisable to wrap this around a function that uses, for example, OpenZeppelin's
* onlyOwner modifier
*
* @param _router address of the deployed Router smart contract
*/
function _setRouter(address _router) internal returns (bool) {
require(_router != address(0), "router cannot be the zero address");
router = IRouter(_router);
return true;
}
/**
* @notice _increaseRouterAllowance is a helper function to increase token allowance for
* the xFUND Router
* Allows this contract to increase the xFUND allowance for the Router contract
* enabling it to pay request fees on behalf of this contract.
* NOTE: it is advisable to wrap this around a function that uses, for example, OpenZeppelin's
* onlyOwner modifier
*
* @param _amount uint256 amount to increase allowance by
*/
function _increaseRouterAllowance(uint256 _amount) internal returns (bool) {
// The context of msg.sender is this contract's address
require(xFUND.increaseAllowance(address(router), _amount), "failed to increase allowance");
return true;
}
/**
* @dev _requestData - initialises a data request. forwards the request to the deployed
* Router smart contract.
*
* @param _dataProvider payable address of the data provider
* @param _fee uint256 fee to be paid
* @param _data bytes32 value of data being requested, e.g. PRICE.BTC.USD.AVG requests
* average price for BTC/USD pair
* @return requestId bytes32 request ID which can be used to track or cancel the request
*/
function _requestData(address _dataProvider, uint256 _fee, bytes32 _data)
internal returns (bytes32) {
bytes32 requestId = makeRequestId(address(this), _dataProvider, address(router), nonces[_dataProvider], _data);
// call the underlying ConsumerLib.sol lib's submitDataRequest function
require(router.initialiseRequest(_dataProvider, _fee, _data));
nonces[_dataProvider] = nonces[_dataProvider].safeAdd(1);
return requestId;
}
/**
* @dev rawReceiveData - Called by the Router's fulfillRequest function
* in order to fulfil a data request. Data providers call the Router's fulfillRequest function
* The request is validated to ensure it has indeed been sent via the Router.
*
* The Router will only call rawReceiveData once it has validated the origin of the data fulfillment.
* rawReceiveData then calls the user defined receiveData function to finalise the fulfilment.
* Contract developers will need to override the abstract receiveData function defined below.
*
* @param _price uint256 result being sent
* @param _requestId bytes32 request ID of the request being fulfilled
* has sent the data
*/
function rawReceiveData(
uint256 _price,
bytes32 _requestId) external
{
// validate it came from the router
require(msg.sender == address(router), "only Router can call");
// call override function in end-user's contract
receiveData(_price, _requestId);
}
/**
* @dev receiveData - should be overridden by contract developers to process the
* data fulfilment in their own contract.
*
* @param _price uint256 result being sent
* @param _requestId bytes32 request ID of the request being fulfilled
*/
function receiveData(
uint256 _price,
bytes32 _requestId
) internal virtual;
/*
* READ FUNCTIONS
*/
/**
* @dev getRouterAddress returns the address of the Router smart contract being used
*
* @return address
*/
function getRouterAddress() external view returns (address) {
return address(router);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILandRegistry {
function mint(
address user,
int16 x,
int16 y
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/ILockShiboshi.sol";
import "./interfaces/ILockLeash.sol";
import "./interfaces/ILandRegistry.sol";
import "./interfaces/ILandAuction.sol";
contract LandAuction is ILandAuction, AccessControl, ReentrancyGuard {
using ECDSA for bytes32;
bytes32 public constant GRID_SETTER_ROLE = keccak256("GRID_SETTER_ROLE");
uint32 constant clearLow = 0xffff0000;
uint32 constant clearHigh = 0x0000ffff;
uint32 constant factor = 0x10000;
uint16 public constant N = 194; // xHigh + 97 + 1
uint16 public constant M = 200; // yHigh + 100 + 1
/*
xLow, yHigh gets mapped to 1,1
transform: x + 97, 100 - y
y_mapped = 100 - y
x_mapped = 97 + x
*/
int16 public constant xLow = -96;
int16 public constant yLow = -99;
int16 public constant xHigh = 96;
int16 public constant yHigh = 99;
enum Stage {
Default,
Bidding,
PrivateSale,
PublicSale
}
struct Bid {
uint256 amount;
address bidder;
}
address public immutable weth;
ILandRegistry public landRegistry;
ILockLeash public lockLeash;
ILockShiboshi public lockShiboshi;
bool public multiBidEnabled;
address public signerAddress;
Stage public currentStage;
int8[N + 10][M + 10] private _categoryBIT;
mapping(int16 => mapping(int16 => Bid)) public getCurrentBid;
mapping(int8 => uint256) public priceOfCategory;
mapping(address => uint256) public winningsBidsOf;
mapping(address => uint32[]) private _allBidsOf;
mapping(address => mapping(uint32 => uint8)) private _statusOfBidsOf;
event CategoryPriceSet(int8 category, uint256 price);
event StageSet(uint256 stage);
event SignerSet(address signer);
event multiBidToggled(bool newValue);
event BidCreated(
address indexed user,
uint32 indexed encXY,
int16 x,
int16 y,
uint256 price,
uint256 time
);
event LandBought(
address indexed user,
uint32 indexed encXY,
int16 x,
int16 y,
uint256 price,
Stage saleStage
);
constructor(
address _weth,
ILandRegistry _landRegistry,
ILockLeash _lockLeash,
ILockShiboshi _lockShiboshi
) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(GRID_SETTER_ROLE, msg.sender);
weth = _weth;
landRegistry = _landRegistry;
lockLeash = _lockLeash;
lockShiboshi = _lockShiboshi;
signerAddress = msg.sender;
}
modifier onlyValid(int16 x, int16 y) {
require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE");
require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE");
_;
}
modifier onlyStage(Stage s) {
require(currentStage == s, "ERR_THIS_STAGE_NOT_LIVE_YET");
_;
}
function weightToCapacity(uint256 weightLeash, uint256 weightShiboshi)
public
pure
returns (uint256)
{
uint256[10] memory QRangeLeash = [
uint256(9),
uint256(30),
uint256(60),
uint256(100),
uint256(130),
uint256(180),
uint256(220),
uint256(300),
uint256(370),
uint256(419)
];
uint256[10] memory QRangeShiboshi = [
uint256(45),
uint256(89),
uint256(150),
uint256(250),
uint256(350),
uint256(480),
uint256(600),
uint256(700),
uint256(800),
uint256(850)
];
uint256[10] memory buckets = [
uint256(1),
uint256(5),
uint256(10),
uint256(20),
uint256(50),
uint256(80),
uint256(100),
uint256(140),
uint256(180),
uint256(200)
];
uint256 capacity;
if (weightLeash > 0) {
for (uint256 i = 9; i >= 0; i = _uncheckedDec(i)) {
if (weightLeash > QRangeLeash[i] * 1e18) {
capacity += buckets[i];
break;
}
}
}
if (weightShiboshi > 0) {
for (uint256 i = 9; i >= 0; i = _uncheckedDec(i)) {
if (weightShiboshi > QRangeShiboshi[i]) {
capacity += buckets[i];
break;
}
}
}
return capacity;
}
function getOutbidPrice(uint256 bidPrice) public pure returns (uint256) {
// 5% more than the current price
return (bidPrice * 21) / 20;
}
function availableCapacityOf(address user) public view returns (uint256) {
uint256 weightLeash = lockLeash.weightOf(user);
uint256 weightShiboshi = lockShiboshi.weightOf(user);
return
weightToCapacity(weightLeash, weightShiboshi) -
winningsBidsOf[user];
}
function getReservePrice(int16 x, int16 y) public view returns (uint256) {
uint256 price = priceOfCategory[getCategory(x, y)];
require(price != 0, "ERR_NOT_UP_FOR_SALE");
return price;
}
function getPriceOf(int16 x, int16 y) public view returns (uint256) {
Bid storage currentBid = getCurrentBid[x][y];
if (currentBid.amount == 0) {
return getReservePrice(x, y);
} else {
// attempt to outbid
return getOutbidPrice(currentBid.amount);
}
}
function getCategory(int16 x, int16 y) public view returns (int8) {
(uint16 x_mapped, uint16 y_mapped) = _transformXY(x, y);
int8 category;
for (uint16 i = x_mapped; i > 0; i = _subLowbit(i)) {
for (uint16 j = y_mapped; j > 0; j = _subLowbit(j)) {
unchecked {
category += _categoryBIT[i][j];
}
}
}
return category;
}
function isShiboshiZone(int16 x, int16 y) public pure returns (bool) {
/*
(12,99) to (48, 65)
(49, 99) to (77, 78)
(76, 77) to (77, 50)
(65, 50) to (75, 50)
*/
if (x >= 12 && x <= 48 && y <= 99 && y >= 65) {
return true;
}
if (x >= 49 && x <= 77 && y <= 99 && y >= 78) {
return true;
}
if (x >= 76 && x <= 77 && y <= 77 && y >= 50) {
return true;
}
if (x >= 65 && x <= 75 && y == 50) {
return true;
}
return false;
}
// List of currently winning bids of this user
function bidInfoOf(address user)
external
view
returns (int16[] memory, int16[] memory)
{
uint256 bidCount = winningsBidsOf[user];
int16[] memory xs = new int16[](bidCount);
int16[] memory ys = new int16[](bidCount);
uint256 ptr;
uint32[] storage allBids = _allBidsOf[user];
uint256 length = allBids.length;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
if (_statusOfBidsOf[user][allBids[i]] == 1) {
(int16 x, int16 y) = _decodeXY(allBids[i]);
xs[ptr] = x;
ys[ptr] = y;
ptr = _uncheckedInc(ptr);
}
}
return (xs, ys);
}
// List of all bids, ever done by this user
function allBidInfoOf(address user)
external
view
returns (int16[] memory, int16[] memory)
{
uint32[] storage allBids = _allBidsOf[user];
uint256 bidCount = allBids.length;
int16[] memory xs = new int16[](bidCount);
int16[] memory ys = new int16[](bidCount);
for (uint256 i = 0; i < bidCount; i = _uncheckedInc(i)) {
(int16 x, int16 y) = _decodeXY(allBids[i]);
xs[i] = x;
ys[i] = y;
}
return (xs, ys);
}
function setGridVal(
int16 x1,
int16 y1,
int16 x2,
int16 y2,
int8 val
) external onlyRole(GRID_SETTER_ROLE) {
(uint16 x1_mapped, uint16 y1_mapped) = _transformXY(x1, y1);
(uint16 x2_mapped, uint16 y2_mapped) = _transformXY(x2, y2);
_updateGrid(x2_mapped + 1, y2_mapped + 1, val);
_updateGrid(x1_mapped, y1_mapped, val);
_updateGrid(x1_mapped, y2_mapped + 1, -val);
_updateGrid(x2_mapped + 1, y1_mapped, -val);
}
function setPriceOfCategory(int8 category, uint256 price)
external
onlyRole(GRID_SETTER_ROLE)
{
priceOfCategory[category] = price;
emit CategoryPriceSet(category, price);
}
function setStage(uint256 stage) external onlyRole(DEFAULT_ADMIN_ROLE) {
currentStage = Stage(stage);
emit StageSet(stage);
}
function setSignerAddress(address signer)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(signer != address(0), "ERR_CANNOT_BE_ZERO_ADDRESS");
signerAddress = signer;
emit SignerSet(signer);
}
function setLandRegistry(address _landRegistry)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
landRegistry = ILandRegistry(_landRegistry);
}
function setLockLeash(address _lockLeash)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
lockLeash = ILockLeash(_lockLeash);
}
function setLockShiboshi(address _lockShiboshi)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
lockShiboshi = ILockShiboshi(_lockShiboshi);
}
function setMultiBid(bool desiredValue)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(multiBidEnabled != desiredValue, "ERR_ALREADY_DESIRED_VALUE");
multiBidEnabled = desiredValue;
emit multiBidToggled(desiredValue);
}
function withdraw(address to, uint256 amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
payable(to).transfer(amount);
}
function bidOne(int16 x, int16 y)
external
payable
onlyStage(Stage.Bidding)
nonReentrant
{
address user = msg.sender;
require(availableCapacityOf(user) != 0, "ERR_NO_BIDS_REMAINING");
require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, msg.value);
}
function bidShiboshiZoneOne(
int16 x,
int16 y,
bytes calldata signature
) external payable onlyStage(Stage.Bidding) nonReentrant {
address user = msg.sender;
require(
_verifySigner(_hashMessage(user), signature),
"ERR_SIGNATURE_INVALID"
);
require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, msg.value);
}
function bidMulti(
int16[] calldata xs,
int16[] calldata ys,
uint256[] calldata prices
) external payable onlyStage(Stage.Bidding) nonReentrant {
require(multiBidEnabled, "ERR_MULTI_BID_DISABLED");
address user = msg.sender;
uint256 length = xs.length;
require(length != 0, "ERR_NO_INPUT");
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH");
uint256 total;
require(
availableCapacityOf(user) >= length,
"ERR_INSUFFICIENT_BIDS_REMAINING"
);
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
total += prices[i];
}
require(msg.value == total, "ERR_INSUFFICIENT_AMOUNT_SENT");
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, prices[i]);
}
}
function bidShiboshiZoneMulti(
int16[] calldata xs,
int16[] calldata ys,
uint256[] calldata prices,
bytes calldata signature
) external payable onlyStage(Stage.Bidding) nonReentrant {
require(multiBidEnabled, "ERR_MULTI_BID_DISABLED");
address user = msg.sender;
require(
_verifySigner(_hashMessage(user), signature),
"ERR_SIGNATURE_INVALID"
);
uint256 length = xs.length;
require(length != 0, "ERR_NO_INPUT");
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH");
uint256 total;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
total += prices[i];
}
require(msg.value == total, "ERR_INSUFFICIENT_AMOUNT_SENT");
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, prices[i]);
}
}
function mintWinningBid(int16[] calldata xs, int16[] calldata ys) external {
require(
currentStage == Stage.PublicSale ||
currentStage == Stage.PrivateSale,
"ERR_MUST_WAIT_FOR_BIDDING_TO_END"
);
uint256 length = xs.length;
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE");
require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE");
address user = getCurrentBid[x][y].bidder;
require(user != address(0), "ERR_NO_BID_FOUND");
landRegistry.mint(user, x, y);
}
}
function mintPrivate(int16 x, int16 y)
external
payable
onlyStage(Stage.PrivateSale)
nonReentrant
{
require(availableCapacityOf(msg.sender) != 0, "ERR_NO_BIDS_REMAINING");
require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE");
_mintPublicOrPrivate(msg.sender, x, y);
emit LandBought(
msg.sender,
_encodeXY(x, y),
x,
y,
msg.value,
Stage.PrivateSale
);
}
function mintPrivateShiboshiZone(
int16 x,
int16 y,
bytes calldata signature
) external payable onlyStage(Stage.PrivateSale) nonReentrant {
require(
_verifySigner(_hashMessage(msg.sender), signature),
"ERR_SIGNATURE_INVALID"
);
require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE");
_mintPublicOrPrivate(msg.sender, x, y);
emit LandBought(
msg.sender,
_encodeXY(x, y),
x,
y,
msg.value,
Stage.PrivateSale
);
}
function mintPublic(int16 x, int16 y)
external
payable
onlyStage(Stage.PublicSale)
nonReentrant
{
_mintPublicOrPrivate(msg.sender, x, y);
emit LandBought(
msg.sender,
_encodeXY(x, y),
x,
y,
msg.value,
Stage.PublicSale
);
}
// transform: +97, +100
function _transformXY(int16 x, int16 y)
internal
pure
onlyValid(x, y)
returns (uint16, uint16)
{
return (uint16(x + 97), uint16(100 - y));
}
function _bid(
address user,
int16 x,
int16 y,
uint256 price
) internal onlyValid(x, y) {
uint32 encXY = _encodeXY(x, y);
Bid storage currentBid = getCurrentBid[x][y];
if (currentBid.amount == 0) {
// first bid on this land
require(
price >= getReservePrice(x, y),
"ERR_INSUFFICIENT_AMOUNT_SENT"
);
} else {
// attempt to outbid
require(user != currentBid.bidder, "ERR_CANNOT_OUTBID_YOURSELF");
require(
price >= getOutbidPrice(currentBid.amount),
"ERR_INSUFFICIENT_AMOUNT_SENT"
);
_safeTransferETHWithFallback(currentBid.bidder, currentBid.amount);
winningsBidsOf[currentBid.bidder] -= 1;
_statusOfBidsOf[currentBid.bidder][encXY] = 2;
}
currentBid.bidder = user;
currentBid.amount = price;
winningsBidsOf[user] += 1;
if (_statusOfBidsOf[user][encXY] == 0) {
// user has never bid on this land earlier
_allBidsOf[user].push(encXY);
}
_statusOfBidsOf[user][encXY] = 1;
emit BidCreated(user, encXY, x, y, price, block.timestamp);
}
function _mintPublicOrPrivate(
address user,
int16 x,
int16 y
) internal onlyValid(x, y) {
Bid storage currentBid = getCurrentBid[x][y];
require(currentBid.amount == 0, "ERR_NOT_UP_FOR_SALE");
require(
msg.value == getReservePrice(x, y),
"ERR_INSUFFICIENT_AMOUNT_SENT"
);
currentBid.bidder = user;
currentBid.amount = msg.value;
winningsBidsOf[user] += 1;
uint32 encXY = _encodeXY(x, y);
_allBidsOf[user].push(encXY);
_statusOfBidsOf[user][encXY] = 1;
landRegistry.mint(user, x, y);
}
function _hashMessage(address sender) private pure returns (bytes32) {
return keccak256(abi.encodePacked(sender));
}
function _verifySigner(bytes32 messageHash, bytes memory signature)
private
view
returns (bool)
{
return
signerAddress ==
messageHash.toEthSignedMessageHash().recover(signature);
}
/**
* @notice Transfer ETH. If the ETH transfer fails, wrap the ETH and try send it as WETH.
*/
function _safeTransferETHWithFallback(address to, uint256 amount) internal {
if (!_safeTransferETH(to, amount)) {
IWETH(weth).deposit{value: amount}();
IERC20(weth).transfer(to, amount);
}
}
/**
* @notice Transfer ETH and return the success status.
* @dev This function only forwards 30,000 gas to the callee.
*/
function _safeTransferETH(address to, uint256 value)
internal
returns (bool)
{
(bool success, ) = to.call{value: value, gas: 30_000}(new bytes(0));
return success;
}
function _uncheckedInc(uint256 i) internal pure returns (uint256) {
unchecked {
return i + 1;
}
}
function _uncheckedDec(uint256 i) internal pure returns (uint256) {
unchecked {
return i - 1;
}
}
function _encodeXY(int16 x, int16 y) internal pure returns (uint32) {
return
((uint32(uint16(x)) * factor) & clearLow) |
(uint32(uint16(y)) & clearHigh);
}
function _decodeXY(uint32 value) internal pure returns (int16 x, int16 y) {
x = _expandNegative16BitCast((value & clearLow) >> 16);
y = _expandNegative16BitCast(value & clearHigh);
}
function _expandNegative16BitCast(uint32 value)
internal
pure
returns (int16)
{
if (value & (1 << 15) != 0) {
return int16(int32(value | clearLow));
}
return int16(int32(value));
}
// Functions for BIT
function _updateGrid(
uint16 x,
uint16 y,
int8 val
) internal {
for (uint16 i = x; i <= N; i = _addLowbit(i)) {
for (uint16 j = y; j <= M; j = _addLowbit(j)) {
unchecked {
_categoryBIT[i][j] += val;
}
}
}
}
function _addLowbit(uint16 i) internal pure returns (uint16) {
unchecked {
return i + uint16(int16(i) & (-int16(i)));
}
}
function _subLowbit(uint16 i) internal pure returns (uint16) {
unchecked {
return i - uint16(int16(i) & (-int16(i)));
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library OOOSafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function safeAdd(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function saveDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function safeMod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20_Ex {
/**
* @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 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) external returns (bool);
/**
* @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) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRouter {
function initialiseRequest(address, uint256, bytes32) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title RequestIdBase
*
* @dev A contract used by ConsumerBase and Router to generate requestIds
*
*/
contract RequestIdBase {
/**
* @dev makeRequestId generates a requestId
*
* @param _dataConsumer address of consumer contract
* @param _dataProvider address of provider
* @param _router address of Router contract
* @param _requestNonce uint256 request nonce
* @param _data bytes32 hex encoded data endpoint
*
* @return bytes32 requestId
*/
function makeRequestId(
address _dataConsumer,
address _dataProvider,
address _router,
uint256 _requestNonce,
bytes32 _data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_dataConsumer, _dataProvider, _router, _requestNonce, _data));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.13;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function transfer(address to, uint256 value) external returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILockShiboshi {
function lockInfoOf(address user)
external
view
returns (
uint256[] memory ids,
uint256 startTime,
uint256 numDays,
address ogUser
);
function weightOf(address user) external view returns (uint256);
function extraShiboshiNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function extraDaysNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function isWinner(address user) external view returns (bool);
function unlockAt(address user) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILockLeash {
function lockInfoOf(address user)
external
view
returns (
uint256 amount,
uint256 startTime,
uint256 numDays,
address ogUser
);
function weightOf(address user) external view returns (uint256);
function extraLeashNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function extraDaysNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function isWinner(address user) external view returns (bool);
function unlockAt(address user) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILandAuction {
function winningsBidsOf(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Returns the integer division of two unsigned integers, reverting on division by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero./
|
function saveDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
| 1,496,177 |
pragma solidity >=0.4.4;
import 'truffle/Assert.sol';
import '../contracts/Common.sol';
import '../contracts/ICO.sol';
import '../contracts/FirstSale.sol';
contract Person {
ICO ico;
function Person(address _ico) {
ico = ICO(_ico);
}
function deposit() payable {
ico.deposit.value(msg.value)();
}
function claim() {
ico.claim();
}
function claimableTokens() returns (uint) {
return ico.claimableTokens();
}
function claimableRefund() returns (uint) {
return ico.claimableRefund();
}
function () payable { }
function acceptOwnership() {
ico.acceptOwnership();
}
}
contract Attacker {
ICO ico;
bool done = false;
function Attacker(address _ico) {
ico = ICO(_ico);
}
function deposit() payable {
ico.deposit.value(msg.value)();
}
function claim() {
ico.claim();
}
function () payable {
bool wasdone = done;
done = true;
if (!wasdone) ico.claim();
}
}
//for testing purposes
//this sale refunds half your money, and buys tokens with the rest
//and mints only upon calling claim()
contract SampleSale is Sale {
uint public startTime;
uint public stopTime;
uint public target;
uint public raised;
uint public collected;
uint public numContributors;
uint price = 100;
mapping(address => uint) public balances;
function SampleSale(uint _time) {
startTime = _time;
stopTime = startTime + 10 days;
}
function buyTokens(address _a, uint _eth, uint _time) returns (uint) {
if (balances[_a] == 0) {
numContributors += 1;
}
balances[_a] += _eth;
raised += _eth / 2;
return 0;
}
function getTokens(address _a) constant returns (uint) {
return price * (balances[_a]) / 2;
}
function getRefund(address _a) constant returns (uint) {
return balances[_a] / 2;
}
function getSoldTokens() constant returns (uint) {
return (raised / 2) * price;
}
function getOwnerEth() constant returns (uint) {
return raised;
}
function isActive(uint time) constant returns (bool) {
return (time >= startTime && time <= stopTime);
}
function isComplete(uint time) constant returns (bool) {
return (time >= stopTime);
}
function tokensPerEth() constant returns (uint) {
return 1;
}
}
//like SampleSale but mints immediately
contract SampleSaleFastMint is SampleSale {
function SampleSaleFastMint(uint _time) SampleSale(_time) {}
function buyTokens(address _a, uint _eth, uint _time) returns (uint) {
if (balances[_a] == 0) {
numContributors += 1;
}
balances[_a] += _eth;
raised += _eth / 2;
return (_eth / 2) * price;
}
function getTokens(address _a) constant returns (uint) {
return 0;
}
}
contract TestController is Owned {
ICO public ico;
uint weiPerDollar = 20;
function TestController() {
owner = msg.sender;
}
function setICO(address _ico) {
ico = ICO(_ico);
}
function startSampleSale() {
address sale = address(new SampleSale(ico.currTime()));
ico.addSale(sale);
}
function startSampleSaleFastMint() {
address sale = address(new SampleSaleFastMint(ico.currTime()));
ico.addSale(sale);
}
function startSampleSaleWithMinimum(uint _minimum) {
address sale = address(new SampleSale(ico.currTime()));
ico.addSale(sale, _minimum);
}
}
contract ICOTest is EventDefinitions {
ICO ico;
TestController con;
Person p1;
Person p2;
Person p3;
Token token;
//for testing we say 10 weis makes an eth
//because dapple only gives us 10 eths to work with
//so let's say 1 ether = 10 dollars = 200 wei
uint weiPerDollar = 20;
uint weiPerEth = 200;
function () payable {}
function eth(uint eth) returns (uint) {
return eth * weiPerEth;
}
function dollars(uint d) returns (uint) {
return d * weiPerDollar;
}
function setUp() {
con = new TestController();
ico = new ICO();
con.setICO(ico);
ico.setController(con);
ico.setAsTest();
token = new Token();
token.setICO(address(ico));
token.setController(con);
ico.setToken(token);
ico.setFakeTime(1);
weiPerEth = ico.weiPerEth();
p1 = new Person(address(ico));
p2 = new Person(address(ico));
p3 = new Person(address(ico));
}
function testFirstSaleNum() {
con.startSampleSale();
ico.setFakeTime(3 days + 2);
Assert.equal(ico.getCurrSale(), 0, "first sale not set");
Assert.equal(ico.nextClaim(address(p1)), 0, "first claim");
}
function testThrowsMinimumPurchase() {
con.startSampleSaleWithMinimum(10);
Sale sale = ico.sales(0);
ico.setFakeTime(3 days + 2);
p1.deposit.value(5)();
}
function testAboveMinimumPurchase() {
con.startSampleSaleWithMinimum(10);
Sale sale = ico.sales(0);
ico.setFakeTime(3 days + 2);
p1.deposit.value(20)();
}
function testBuy() {
// expectEventsExact(ico); //i did it
uint weis = 1000;
con.startSampleSale();
Sale sale = ico.sales(0);
logSaleStart(sale.startTime(), sale.stopTime());
ico.setFakeTime(3 days + 2);
Assert.equal(ico.currSaleActive(), true, "active");
Assert.equal(ico.currSaleComplete(), false, "complete");
p1.deposit.value(weis)();
logPurchase(address(p1), weis);
Assert.equal(p1.claimableRefund(), 0, "incomplete refund");
Assert.equal(p1.claimableTokens(), 0, "incomplete tokens");
ico.addDays(20);
Assert.equal(ico.currSaleActive(), false, "2 active");
Assert.equal(ico.currSaleComplete(), true, "2 complete");
Assert.equal(p1.claimableRefund(), weis / 2, "complete refund");
Assert.equal(p1.claimableTokens(), 100 * weis / 2, "complete tokens");
}
function testClaim() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(3 days + 2);
Assert.equal(ico.currSaleActive(), true, "active");
Assert.equal(ico.currSaleComplete(), false, "complete");
p1.deposit.value(weis)();
logPurchase(address(p1), weis);
Assert.equal(p1.claimableRefund(), 0, "incomplete refund");
Assert.equal(p1.claimableTokens(), 0, "incomplete tokens");
ico.addDays(20);
Assert.equal(ico.currSaleActive(), false, "2 active");
Assert.equal(ico.currSaleComplete(), true, "2 complete");
Assert.equal(p1.claimableRefund(), weis / 2, "complete refund");
Assert.equal(p1.claimableTokens(), 100 * weis / 2, "complete tokens");
p1.claim();
Assert.equal(ico.nextClaim(address(p1)), 1, "next claim");
Assert.equal(p1.balance, weis / 2, "p1 balance");
Assert.equal(p1.claimableRefund(), 0, "p1 refund after claim");
Assert.equal(p1.claimableTokens(), 0, "p1 tokens after claim");
}
function testClaimFastMint() {
uint weis = 1000;
con.startSampleSaleFastMint();
ico.setFakeTime(3 days + 2);
Assert.equal(ico.currSaleActive(), true, "active");
Assert.equal(ico.currSaleComplete(), false, "complete");
p1.deposit.value(weis)();
logPurchase(address(p1), weis);
Assert.equal(token.balanceOf(address(p1)), 100 * weis / 2, "fast mint");
Assert.equal(p1.claimableRefund(), 0, "incomplete refund");
Assert.equal(p1.claimableTokens(), 0, "incomplete tokens");
ico.addDays(20);
Assert.equal(ico.currSaleActive(), false, "2 active");
Assert.equal(ico.currSaleComplete(), true, "2 complete");
Assert.equal(p1.claimableRefund(), weis / 2, "complete refund");
Assert.equal(p1.claimableTokens(), 0, "complete tokens");
p1.claim();
Assert.equal(ico.nextClaim(address(p1)), 1, "next claim");
Assert.equal(p1.balance, weis / 2, "p1 balance");
Assert.equal(p1.claimableRefund(), 0, "p1 refund after claim");
Assert.equal(p1.claimableTokens(), 0, "p1 tokens after claim");
}
function testClaimFor() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(4 days);
p1.deposit.value(weis)();
ico.addDays(20);
Assert.equal(p1.claimableRefund(), weis / 2, "complete refund");
Assert.equal(p1.claimableTokens(), 100 * weis / 2, "complete tokens");
ico.addDays(400);
ico.claimFor(address(p1), address(p2));
Assert.equal(p2.balance, weis / 2, "recipient balance");
Assert.equal(token.balanceOf(address(p2)), 100 * weis / 2, "recip tokens");
Assert.equal(p2.claimableTokens(), 0, "recip claimable tokens");
Assert.equal(p2.claimableRefund(), 0, "recip claimable refund");
Assert.equal(p1.claimableTokens(), 0, "p1 claimable tokens 2");
Assert.equal(p1.claimableRefund(), 0, "p1 claimable refund 2");
}
function testClaimForTooSoon() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(4 days);
p1.deposit.value(weis)();
ico.addDays(20);
Assert.equal(p1.claimableRefund(), weis / 2, "complete refund");
Assert.equal(p1.claimableTokens(), 100 * weis / 2, "complete tokens");
ico.claimFor(address(p1), address(p2));
Assert.equal(p2.balance, 0, "recipient balance");
Assert.equal(token.balanceOf(address(p2)), 0, "recip tokens");
Assert.equal(p1.claimableRefund(), weis / 2, "p1 claimable refund 2");
Assert.equal(p1.claimableTokens(), 100 * weis / 2, "p1 claimable tokens 2");
}
function testDoubleClaim() {
//two people deposit max so each should get half back
//one tries to do it twice and take it all
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(4 days);
p1.deposit.value(weis)();
p2.deposit.value(weis)();
ico.addDays(20);
p1.claim();
p1.claim();
Assert.equal(p1.balance, 500, "p1 balance");
Assert.equal(token.balanceOf(address(p1)), 50000, "p1 tokens");
p2.claim();
Assert.equal(p2.balance, 500, "p2 balance");
Assert.equal(token.balanceOf(address(p2)), 50000, "p2 tokens");
}
function testThrowReentrantAttack () {
//two people deposit max so each should get half back
//one tries to do it twice via reentrance
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(4 days);
p1.deposit.value(weis)();
Attacker a2 = new Attacker(ico);
a2.deposit.value(weis)();
ico.addDays(20);
a2.claim();
p1.claim();
Assert.equal(p1.balance, 500, "p1 balance");
Assert.equal(token.balanceOf(address(p1)), 100 * weis / 2, "p1 tokens");
a2.claim();
Assert.equal(a2.balance, 500, "a2 balance");
Assert.equal(token.balanceOf(address(a2)), 100 * weis / 2, "a2 tokens");
}
function testMulticlaim() {
uint weis = 1000;
//DEPOSIT IN FIRST SALE
con.startSampleSale();
ico.setFakeTime(4 days);
p1.deposit.value(weis)();
ico.addDays(20);
Assert.equal(ico.currSaleActive(), false, "0 active");
Assert.equal(ico.currSaleComplete(), true, "0 complete");
//DEPOSIT IN SECOND SALE
con.startSampleSale();
ico.addDays(4);
Assert.equal(ico.currSaleActive(), true, "1 active");
Assert.equal(ico.currSaleComplete(), false, "1 complete");
p1.deposit.value(weis)();
ico.addDays(20);
Assert.equal(ico.currSaleActive(), false, "1 active b");
Assert.equal(ico.currSaleComplete(), true, "1 complete b");
//DEPOSIT IN THIRD SALE
con.startSampleSale();
ico.addDays(4);
Assert.equal(ico.currSaleActive(), true, "2 active");
Assert.equal(ico.currSaleComplete(), false, "2 complete");
p1.deposit.value(weis)();
//DO A CLAIM WHILE THIRD SALE RUNNING
//so this is a claim on two sales
p1.claim();
//at this point we should have tokens and refund from first two sales
Assert.equal(p1.balance, 2 * (weis / 2), "balance2");
Assert.equal(token.balanceOf(address(p1)), 2 * (100 * weis / 2), "tokens2");
//END THIRD SALE AND CLAIM
ico.addDays(20);
p1.claim();
//now should have tokens and refund frmo all three sales
Assert.equal(p1.balance, 3 * (weis / 2), "balance3");
Assert.equal(token.balanceOf(address(p1)), 3 * (100 * weis / 2), "tokens3");
}
function testClaimWithActiveSale() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(4 days);
p1.deposit.value(weis)();
p1.claim();
Assert.equal(address(p1).balance, 0, "eth balance");
Assert.equal(token.balanceOf(address(p1)), 0, "token balance");
}
function testOwnerWithdraw() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(3 days + 2);
p1.deposit.value(weis)();
ico.addDays(20);
Assert.equal(address(ico).balance, 1000, "pre-withdraw");
uint prewithdraw = this.balance;
ico.claimOwnerEth(0);
Assert.equal(address(ico).balance, 500, "withdraw");
Assert.equal(this.balance, prewithdraw + 500, "post-withdraw");
}
function testTopup() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(3 days + 2);
p1.deposit.value(weis)();
Assert.equal(ico.balance, weis, "a");
Assert.equal(ico.topUpAmount(), 0, "b");
ico.topUp.value(10)();
Assert.equal(ico.balance, weis + 10, "c");
Assert.equal(ico.topUpAmount(), 10, "d");
ico.withdrawTopUp();
Assert.equal(ico.balance, weis, "e");
Assert.equal(ico.topUpAmount(), 0, "f");
ico.withdrawTopUp();
Assert.equal(ico.balance, weis, "g");
}
function testBuyerCount() {
con.startSampleSale();
Sale sale = ico.sales(0);
ico.setFakeTime(3 days + 2);
p1.deposit.value(1)();
p1.deposit.value(2)();
p3.deposit.value(2)();
Assert.equal(ico.numContributors(0), 2, "count");
}
function testStopAndRefund() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(3 days + 2);
p1.deposit.value(weis)();
ico.allStop();
ico.allStart();
p1.deposit.value(weis)();
ico.allStop();
ico.emergencyRefund(address(p1), weis * 2);
Assert.equal(address(p1).balance, weis * 2, "emergency refund");
}
function testThrowStop() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(3 days + 2);
ico.allStop();
p1.deposit.value(weis)();
}
function testThrowEmergencyRefundWithoutStop() {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(3 days + 2);
p1.deposit.value(weis)();
ico.emergencyRefund(address(p1), weis);
}
function testSetPayee() {
ico.changePayee(0x0);
Assert.equal(ico.payee(), 0x0, "payee");
}
/* Fix this test */
function testPurchaseByToken() {
uint weis = 1000;
con.startSampleSaleFastMint();
ico.setFakeTime(3 days + 2);
Assert.equal(ico.currSaleActive(), true, "active");
Assert.equal(ico.currSaleComplete(), false, "complete");
Assert.equal(ico.tokensPerEth(), 1, "tokens per eth");
Assert.equal(weiPerEth, 200, "wei per eth");
address tok = address(new Token());
ico.depositTokens(address(p1), 0x1, weis, 100, bytes32(0x123));
Assert.equal(token.balanceOf(address(p1)), 1000 / weiPerEth, "fast mint");
Assert.equal(p1.claimableRefund(), 0, "incomplete refund");
Assert.equal(p1.claimableTokens(), 0, "incomplete tokens");
}
function testThrowsPurchaseByToken() {
uint weis = 1000;
con.startSampleSaleFastMint();
ico.setFakeTime(3 days + 2);
Assert.equal(ico.currSaleActive(), true, "active");
Assert.equal(ico.currSaleComplete(), false, "complete");
ico.depositTokens(address(p1), 0x1, weis, 100, bytes32(0x123));
ico.depositTokens(address(p1), 0x1, weis, 100, bytes32(0x123));
}
function testChangeOwner() {
ico.changeOwner(address(p1));
p1.acceptOwnership();
Assert.equal(ico.owner(), address(p1), "owner");
}
}
|
two people deposit max so each should get half backone tries to do it twice via reentrance
|
function testThrowReentrantAttack () {
uint weis = 1000;
con.startSampleSale();
ico.setFakeTime(4 days);
p1.deposit.value(weis)();
Attacker a2 = new Attacker(ico);
a2.deposit.value(weis)();
ico.addDays(20);
a2.claim();
p1.claim();
Assert.equal(p1.balance, 500, "p1 balance");
Assert.equal(token.balanceOf(address(p1)), 100 * weis / 2, "p1 tokens");
a2.claim();
Assert.equal(a2.balance, 500, "a2 balance");
Assert.equal(token.balanceOf(address(a2)), 100 * weis / 2, "a2 tokens");
}
| 15,807,575 |
./full_match/80001/0xB3CB2E91eDD65692eee7429E294bDE816855D20A/sources/contracts/ERC721BaseOptimized.sol
|
See {ERC721-setApprovalForAll}.
|
function setApprovalForAll(
address operator,
bool approved
) public virtual override(ERC721A) onlyAllowedOperatorApproval(operator) {
super.setApprovalForAll(operator, approved);
}
| 5,667,262 |
// 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 "../../../solidity-utils/contracts/math/FixedPoint.sol";
/**
* @dev Library for compressing and uncompresing numbers by using smaller types.
* All values are 18 decimal fixed-point numbers in the [0.0, 1.0] range,
* so heavier compression (fewer bits) results in fewer decimals.
*/
library WeightCompression {
uint256 private constant _UINT31_MAX = 2**(31) - 1;
using FixedPoint for uint256;
/**
* @dev Convert a 16-bit value to full FixedPoint
*/
function uncompress16(uint256 value) internal pure returns (uint256) {
return value.mulUp(FixedPoint.ONE).divUp(type(uint16).max);
}
/**
* @dev Compress a FixedPoint value to 16 bits
*/
function compress16(uint256 value) internal pure returns (uint256) {
return value.mulUp(type(uint16).max).divUp(FixedPoint.ONE);
}
/**
* @dev Convert a 31-bit value to full FixedPoint
*/
function uncompress31(uint256 value) internal pure returns (uint256) {
return value.mulUp(FixedPoint.ONE).divUp(_UINT31_MAX);
}
/**
* @dev Compress a FixedPoint value to 31 bits
*/
function compress31(uint256 value) internal pure returns (uint256) {
return value.mulUp(_UINT31_MAX).divUp(FixedPoint.ONE);
}
/**
* @dev Convert a 32-bit value to full FixedPoint
*/
function uncompress32(uint256 value) internal pure returns (uint256) {
return value.mulUp(FixedPoint.ONE).divUp(type(uint32).max);
}
/**
* @dev Compress a FixedPoint value to 32 bits
*/
function compress32(uint256 value) internal pure returns (uint256) {
return value.mulUp(type(uint32).max).divUp(FixedPoint.ONE);
}
/**
* @dev Convert a 64-bit value to full FixedPoint
*/
function uncompress64(uint256 value) internal pure returns (uint256) {
return value.mulUp(FixedPoint.ONE).divUp(type(uint64).max);
}
/**
* @dev Compress a FixedPoint value to 64 bits
*/
function compress64(uint256 value) internal pure returns (uint256) {
return value.mulUp(type(uint64).max).divUp(FixedPoint.ONE);
}
}
|
Convert a 16-bit value to full FixedPoint/
|
function uncompress16(uint256 value) internal pure returns (uint256) {
return value.mulUp(FixedPoint.ONE).divUp(type(uint16).max);
}
| 949,626 |
pragma solidity 0.5.17;
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);
}
contract IFactRegistry {
/*
Returns true if the given fact was previously registered in the contract.
*/
function isValid(bytes32 fact)
external view
returns(bool);
}
contract PublicInputOffsets {
// The following constants are offsets of data expected in the public input.
uint256 internal constant OFFSET_LOG_TRACE_LENGTH = 0;
uint256 internal constant OFFSET_VDF_OUTPUT_X = 1;
uint256 internal constant OFFSET_VDF_OUTPUT_Y = 2;
uint256 internal constant OFFSET_VDF_INPUT_X = 3;
uint256 internal constant OFFSET_VDF_INPUT_Y = 4;
// The Verifier derives the number of iterations from the log of the trace length.
// The Vending contract uses the number of iterations.
uint256 internal constant OFFSET_N_ITER = 0;
}
contract VendingMachineERC20 is PublicInputOffsets {
// Emitted by addPayment() when a user makes a payment for a randomness.
event LogNewPayment(uint256 seed, uint256 n_iter, uint256 paymentAmount);
// Emitted by reclaimPayment() when a user reclaims a payment they made.
event LogPaymentReclaimed(
address sender,
uint256 seed,
uint256 n_iter,
uint256 tag,
uint256 reclaimedAmount
);
// Emitted by registerAndCollect() when a new randomness is registered.
event LogNewRandomness(uint256 seed, uint256 n_iter, bytes32 randomness);
struct Payment {
// The last time a user sent a payment for given (sender, seed, n_iter, tag).
uint256 timeSent;
// The sum of those payments.
uint256 amount;
}
// Mapping: (seed, n_iters) -> total_amount.
// Represents prize amount for VDF(seed, n_iter) solver.
// prizes(seed, n_iter) is always equal to the sum of
// payments(sender, seed, n_iters, tag) over all 'sender' and 'tag'.
mapping(uint256 => mapping(uint256 => uint256)) public prizes;
// Mapping: (sender, seed, n_iters, tag) -> Payment.
// Information to support reclaiming of payments.
// 'tag' is used to allow a wrapper contract to distinguish between different users.
mapping(address => mapping(uint256 => mapping(uint256 => mapping(uint256 => Payment))))
public payments;
// Mapping: (seed, n_iters) -> randomness.
mapping(uint256 => mapping(uint256 => bytes32)) public registeredRandomness;
// Mapping: address -> isOwner.
mapping(address => bool) owners;
// The Verifier contracts verifies the proof of the VDF.
IFactRegistry public verifierContract;
// The address of ERC20 tokens being accepted as payments.
address public tokenAddress;
uint256 internal constant PRIME = 0x30000003000000010000000000000001;
uint256 internal constant PUBLIC_INPUT_SIZE = 5;
uint256 internal constant RECLAIM_DELAY = 1 days;
// Modifiers.
modifier onlyOwner {
require(owners[msg.sender], "ONLY_OWNER");
_;
}
modifier randomnessNotRegistered(uint256 seed, uint256 n_iter) {
require(
registeredRandomness[seed][n_iter] == 0,
"REGSITERED_RANDOMNESS"
);
_;
}
constructor(address verifierAddress, address token) public {
owners[msg.sender] = true;
verifierContract = IFactRegistry(verifierAddress);
tokenAddress = token;
}
function addOwner(address newOwner) external onlyOwner {
owners[newOwner] = true;
}
function removeOwner(address removedOwner) external onlyOwner {
require(msg.sender != removedOwner, "CANT_REMOVE_SELF");
owners[removedOwner] = false;
}
/*
Adds a payment from msg.sender, and updates timeSent to 'now'.
Note - the sender must make an allowance first.
*/
function addPayment(
uint256 seed,
uint256 n_iter,
uint256 tag,
uint256 paymentAmount
) external randomnessNotRegistered(seed, n_iter) {
// Sends the payment from the user to the contract.
transferIn(paymentAmount);
// Updates mapping.
payments[msg.sender][seed][n_iter][tag].amount += paymentAmount;
payments[msg.sender][seed][n_iter][tag].timeSent = now;
prizes[seed][n_iter] += paymentAmount;
emit LogNewPayment(seed, n_iter, paymentAmount);
}
/*
Allows a user to reclaim their payment if it was not already served and RECLAIM_DELAY has
passed since the last payment.
*/
function reclaimPayment(
uint256 seed,
uint256 n_iter,
uint256 tag
) external randomnessNotRegistered(seed, n_iter) {
Payment memory userPayment = payments[msg.sender][seed][n_iter][tag];
// Make sure a payment is available to reclaim.
require(userPayment.amount > 0, "NO_PAYMENT");
// Make sure enough time has passed.
uint256 lastPaymentTime = userPayment.timeSent;
uint256 releaseTime = lastPaymentTime + RECLAIM_DELAY;
assert(releaseTime >= RECLAIM_DELAY);
// solium-disable-next-line security/no-block-members
require(now >= releaseTime, "PAYMENT_LOCKED");
// Deduct reclaimed payment from mappings.
prizes[seed][n_iter] -= userPayment.amount;
payments[msg.sender][seed][n_iter][tag].amount = 0;
// Send the payment back to the user.
transferOut(userPayment.amount);
emit LogPaymentReclaimed(
msg.sender,
seed,
n_iter,
tag,
userPayment.amount
);
}
function registerAndCollect(
uint256 seed,
uint256 n_iter,
uint256 vdfOutputX,
uint256 vdfOutputY
) external onlyOwner randomnessNotRegistered(seed, n_iter) {
registerNewRandomness(seed, n_iter, vdfOutputX, vdfOutputY);
transferOut(prizes[seed][n_iter]);
}
/*
Registers a new randomness if vdfOutputX and vdfOutputY are valid field elements and the
fact (n_iter, vdfInputX, vdfInputY, vdfOutputX, vdfOutputY) is valid fact in the Verifier.
*/
function registerNewRandomness(
uint256 seed,
uint256 n_iter,
uint256 vdfOutputX,
uint256 vdfOutputY
) internal {
require(vdfOutputX < PRIME && vdfOutputY < PRIME, "INVALID_VDF_OUTPUT");
(uint256 vdfInputX, uint256 vdfInputY) = seed2vdfInput(seed);
uint256[PUBLIC_INPUT_SIZE] memory proofPublicInput;
proofPublicInput[OFFSET_N_ITER] = n_iter;
proofPublicInput[OFFSET_VDF_INPUT_X] = vdfInputX;
proofPublicInput[OFFSET_VDF_INPUT_Y] = vdfInputY;
proofPublicInput[OFFSET_VDF_OUTPUT_X] = vdfOutputX;
proofPublicInput[OFFSET_VDF_OUTPUT_Y] = vdfOutputY;
require(
verifierContract.isValid(
keccak256(abi.encodePacked(proofPublicInput))
),
"FACT_NOT_REGISTERED"
);
// The randomness is the hash of the VDF output and the string "veedo".
bytes32 randomness = keccak256(
abi.encodePacked(
proofPublicInput[OFFSET_VDF_OUTPUT_X],
proofPublicInput[OFFSET_VDF_OUTPUT_Y],
"veedo"
)
);
registeredRandomness[seed][n_iter] = randomness;
emit LogNewRandomness(seed, n_iter, randomness);
}
/*
Transfers funds from the contract to msg.sender.
*/
function transferOut(uint256 amount) internal {
safeERC20Call(
address(tokenAddress),
abi.encodeWithSelector(
IERC20(0).transfer.selector,
msg.sender,
amount
)
);
}
/*
Transfers funds from msg.sender to the contract.
*/
function transferIn(uint256 amount) internal {
safeERC20Call(
address(tokenAddress),
abi.encodeWithSelector(
IERC20(0).transferFrom.selector,
msg.sender,
address(this),
amount
)
);
}
/*
Safe wrapper around ERC20 calls.
This is required because many deployed ERC20 contracts don't return a value.
See https://github.com/ethereum/solidity/issues/4116.
*/
function safeERC20Call(address tokenAddress, bytes memory callData)
internal
{
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory returndata) = address(tokenAddress).call(
callData
);
require(success, string(returndata));
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "ERC20_OPERATION_FAILED");
}
}
/*
Generates VDF inputs from seed.
*/
function seed2vdfInput(uint256 seed)
public
pure
returns (uint256, uint256)
{
uint256 vdfInput = uint256(keccak256(abi.encodePacked(seed, "veedo")));
uint256 vdfInputX = vdfInput & ((1 << 125) - 1);
uint256 vdfInputY = ((vdfInput >> 125) & ((1 << 125) - 1));
return (vdfInputX, vdfInputY);
}
}
|
solium-disable-next-line security/no-low-level-calls
|
function safeERC20Call(address tokenAddress, bytes memory callData)
internal
{
(bool success, bytes memory returndata) = address(tokenAddress).call(
callData
);
require(success, string(returndata));
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "ERC20_OPERATION_FAILED");
}
}
Generates VDF inputs from seed.
| 7,493,826 |
./full_match/1/0x341956C0c653d3348f86d6278f10dD52071312EE/sources/browser/CETO.sol
|
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) {
return true;
}
| 8,410,970 |
// SPDX-License-Identifier: MIT
/**
* @authors: [@hbarcelos]
* @reviewers: [@ferittuncer*, @fnanni-0, @nix1g]
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity ^0.7.2;
import "@kleros/erc-792/contracts/IArbitrator.sol";
import "@kleros/erc-792/contracts/IArbitrable.sol";
import "@kleros/erc-792/contracts/erc-1497/IEvidence.sol";
import "./dependencies/IAMB.sol";
import "./ArbitrationProxyInterfaces.sol";
contract RealitioForeignArbitrationProxy is IForeignArbitrationProxy, IArbitrable, IEvidence {
/// @dev The contract governor. TRUSTED.
address public governor = msg.sender;
/// @dev The address of the arbitrator. TRUSTED.
IArbitrator public immutable arbitrator;
/// @dev The extra data used to raise a dispute in the arbitrator.
bytes public arbitratorExtraData;
/// @dev The ID of the MetaEvidence for disputes.
uint256 public metaEvidenceID;
/// @dev The number of choices for the arbitrator.
uint256 public constant NUMBER_OF_CHOICES_FOR_ARBITRATOR = (2**256) - 2;
/// @dev ArbitraryMessageBridge contract address. TRUSTED.
IAMB public immutable amb;
/// @dev Address of the counter-party proxy on the Home Chain. TRUSTED.
address public homeProxy;
/// @dev The chain ID where the home proxy is deployed.
uint256 public homeChainId;
/// @dev The path for the Terms of Service for Kleros as an arbitrator for Realitio.
string public termsOfService;
enum Status {None, Requested, Created, Failed}
struct Arbitration {
// Status of the arbitration.
Status status;
// Address that made the arbitration request.
address payable requester;
// The deposit paid by the requester at the time of the arbitration.
uint256 deposit;
}
/// @dev Tracks arbitration requests for question ID.
mapping(bytes32 => Arbitration) public arbitrations;
/// @dev Associates dispute IDs to question IDs.
mapping(uint256 => bytes32) public disputeIDToQuestionID;
/**
* @notice Should be emitted when the arbitration is requested.
* @param _questionID The ID of the question to be arbitrated.
* @param _answer The answer provided by the requester.
* @param _requester The requester.
*/
event ArbitrationRequested(bytes32 indexed _questionID, bytes32 _answer, address indexed _requester);
/**
* @notice Should be emitted when the dispute is created.
* @param _questionID The ID of the question to be arbitrated.
* @param _disputeID The ID of the dispute.
*/
event ArbitrationCreated(bytes32 indexed _questionID, uint256 indexed _disputeID);
/**
* @notice Should be emitted when the dispute could not be created.
* @dev This will happen if there is an increase in the arbitration fees
* between the time the arbitration is made and the time it is acknowledged.
* @param _questionID The ID of the question to be arbitrated.
*/
event ArbitrationFailed(bytes32 indexed _questionID);
/**
* @notice Should be emitted when the arbitration is canceled by the Home Chain.
* @param _questionID The ID of the question to be arbitrated.
*/
event ArbitrationCanceled(bytes32 indexed _questionID);
modifier onlyArbitrator() {
require(msg.sender == address(arbitrator), "Only arbitrator allowed");
_;
}
modifier onlyGovernor() {
require(msg.sender == governor, "Only governor allowed");
_;
}
modifier onlyHomeProxy() {
require(msg.sender == address(amb), "Only AMB allowed");
require(amb.messageSourceChainId() == bytes32(homeChainId), "Only home chain allowed");
require(amb.messageSender() == homeProxy, "Only home proxy allowed");
_;
}
modifier onlyIfInitialized() {
require(homeProxy != address(0), "Not initialized yet");
_;
}
/**
* @notice Creates an arbitration proxy on the foreign chain.
* @dev Contract will still require initialization before being usable.
* @param _amb ArbitraryMessageBridge contract address.
* @param _arbitrator Arbitrator contract address.
* @param _arbitratorExtraData The extra data used to raise a dispute in the arbitrator.
* @param _metaEvidence The URI of the meta evidence file.
* @param _termsOfService The path for the Terms of Service for Kleros as an arbitrator for Realitio.
*/
constructor(
IAMB _amb,
IArbitrator _arbitrator,
bytes memory _arbitratorExtraData,
string memory _metaEvidence,
string memory _termsOfService
) {
amb = _amb;
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
termsOfService = _termsOfService;
emit MetaEvidence(metaEvidenceID, _metaEvidence);
}
/**
* @notice Changes the address of a new governor.
* @param _governor The address of the new governor.
*/
function changeGovernor(address _governor) external onlyGovernor {
governor = _governor;
}
/**
* @notice Sets the address of the arbitration proxy on the Home Chain.
* @param _homeProxy The address of the proxy.
* @param _homeChainId The chain ID where the home proxy is deployed.
*/
function setHomeProxy(address _homeProxy, uint256 _homeChainId) external onlyGovernor {
require(homeProxy == address(0), "Home proxy already set");
homeProxy = _homeProxy;
homeChainId = _homeChainId;
}
/**
* @notice Changes the meta evidence used for disputes.
* @param _metaEvidence URI to the new meta evidence file.
*/
function changeMetaEvidence(string calldata _metaEvidence) external onlyGovernor {
metaEvidenceID += 1;
emit MetaEvidence(metaEvidenceID, _metaEvidence);
}
/**
* @notice Changes the terms of service for Realitio.
* @param _termsOfService URI to the new Terms of Service file.
*/
function changeTermsOfService(string calldata _termsOfService) external onlyGovernor {
termsOfService = _termsOfService;
}
/**
* @notice Requests arbitration for given question ID.
* @dev Can be executed only if the contract has been initialized.
* @param _questionID The ID of the question.
* @param _contestedAnswer The answer the requester deems to be incorrect.
*/
function requestArbitration(bytes32 _questionID, bytes32 _contestedAnswer) external payable onlyIfInitialized {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.None, "Arbitration already requested");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(msg.value >= arbitrationCost, "Deposit value too low");
arbitration.status = Status.Requested;
arbitration.requester = msg.sender;
arbitration.deposit = msg.value;
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationRequest.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID, _contestedAnswer, msg.sender);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationRequested(_questionID, _contestedAnswer, msg.sender);
}
/**
* @notice Requests arbitration for given question ID.
* @param _questionID The ID of the question.
*/
function acknowledgeArbitration(bytes32 _questionID) external override onlyHomeProxy {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
if (arbitration.deposit >= arbitrationCost) {
try
arbitrator.createDispute{value: arbitrationCost}(NUMBER_OF_CHOICES_FOR_ARBITRATOR, arbitratorExtraData)
returns (uint256 disputeID) {
disputeIDToQuestionID[disputeID] = _questionID;
// At this point, arbitration.deposit is guaranteed to be greater than or equal to the arbitration cost.
uint256 remainder = arbitration.deposit - arbitrationCost;
arbitration.status = Status.Created;
arbitration.deposit = 0;
if (remainder > 0) {
arbitration.requester.send(remainder);
}
emit ArbitrationCreated(_questionID, disputeID);
emit Dispute(arbitrator, disputeID, metaEvidenceID, uint256(_questionID));
} catch {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID);
}
} else {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID);
}
}
/**
* @notice Cancels the arbitration.
* @param _questionID The ID of the question.
*/
function cancelArbitration(bytes32 _questionID) external override onlyHomeProxy {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
arbitration.requester.send(arbitration.deposit);
delete arbitrations[_questionID];
emit ArbitrationCanceled(_questionID);
}
/**
* @notice Cancels the arbitration in case the dispute could not be created.
* @param _questionID The ID of the question.
*/
function handleFailedDisputeCreation(bytes32 _questionID) external onlyIfInitialized {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.Failed, "Invalid arbitration status");
arbitration.requester.send(arbitration.deposit);
delete arbitrations[_questionID];
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationFailure.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationCanceled(_questionID);
}
/**
* @notice Rules a specified dispute.
* @dev Note that 0 is reserved for "Unable/refused to arbitrate" and we map it to `bytes32(-1)` which has a similar connotation in Realitio.
* @param _disputeID The ID of the dispute in the ERC792 arbitrator.
* @param _ruling The ruling given by the arbitrator.
*/
function rule(uint256 _disputeID, uint256 _ruling) external override onlyArbitrator {
bytes32 questionID = disputeIDToQuestionID[_disputeID];
Arbitration storage arbitration = arbitrations[questionID];
require(arbitration.status == Status.Created, "Invalid arbitration status");
delete arbitrations[questionID];
delete disputeIDToQuestionID[_disputeID];
// Realitio ruling is shifted by 1 compared to Kleros.
// For example, jurors refusing to rule is `0` on Kleros, but uint(-1) on Realitio.
// The line below could be written more explicitly as:
// bytes32(_ruling == 0 ? uint256(-1) : _ruling - 1)
// But the way it is written saves some gas.
bytes32 answer = bytes32(_ruling - 1);
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationAnswer.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, questionID, answer);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit Ruling(arbitrator, _disputeID, _ruling);
}
/**
* @notice Gets the fee to create a dispute.
* @return The fee to create a dispute.
*/
function getDisputeFee(bytes32 questionID) external view override returns (uint256) {
return arbitrator.arbitrationCost(arbitratorExtraData);
}
}
|
Changes the terms of service for Realitio. _termsOfService URI to the new Terms of Service file./
|
function changeTermsOfService(string calldata _termsOfService) external onlyGovernor {
termsOfService = _termsOfService;
}
| 2,472,519 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/payment/PullPayment.sol";
import "./ConsortiumAlliance.sol";
/**
* @title FlightInsuranceHandler
* @dev Provides specific business logic for airlines', flights' and insurances registration.
*
* - As a delegate of ConsortiumAlliance, airlines are registered
* as affiliates, passengers as insurees and flight insurances as
* insurance deposits.
*
* - Trusted Oracles match the request index code, and agree on flight status
* to resolve insurances.
*
* - Unreedemable insurances are credited to the shared consortium account,
* whereas insurances for flights resolved with LATE_AIRLINE status code
* result in a escrow account being credited with the premium.
*
* - Insurees shall withdraw the funds from said escrow account.
*
* - see also ConsortiumAlliance contract.
*/
contract FlightInsuranceHandler is Ownable, AccessControl, PullPayment {
ConsortiumAlliance private consortium;
uint8 private nonce = 0;
// --------------- FLIGHT -------------------------------------------------
enum FlightStatus {
UNKNOWN,
ON_TIME,
LATE_AIRLINE,
LATE_WEATHER,
LATE_TECHNICAL,
LATE_OTHER
}
struct Flight {
bool isRegistered;
address airline;
uint256 updatedTimestamp;
FlightStatus status;
}
mapping(bytes32 => Flight) public flights;
bytes32[] private flightKeys;
// --------------- FLIGHT INSURANCE ---------------------------------------
mapping(bytes32 => bytes32[]) private flightInsurances;
// --------------- ORACLES ------------------------------------------------
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
mapping(address => Oracle) public oracles;
struct ResponseInfo {
address requester;
bool isOpen;
mapping(uint8 => address[]) responses; // status => oracles
}
mapping(bytes32 => ResponseInfo) private oracleResponses; // Key = hash(index, flightKey)
// --------------- EVENTS -------------------------------------------------
event LogAdminRegistered(address admin);
event LogDelegateRegistered(address _address);
event LogAirlineRegistered(address indexed airline, string title);
event LogOracleRegistered(address oracle);
event LogFlightRegistered(
bytes32 key,
address indexed airline,
bytes32 hexcode,
uint256 timestamp
);
event LogFlightInsuranceRegistered(
bytes32 insurance,
bytes32 flight,
address indexed insuree
);
event LogFlightStatusRequested(
bytes32 flight,
bytes32 response,
uint8 index
);
event LogFlightStatusResolved(bytes32 flight, FlightStatus status);
event LogOracleReport(address oracle, bytes32 flight, FlightStatus status);
event LogFlightStatusProcessed(bytes32 flight);
event LogInsureeCredited(bytes32 flight, bytes32 key);
event LogConsortiumCredited(bytes32 flight, bytes32 key);
// --------------- MODIFIERS ----------------------------------------------
modifier onlyOperational() {
require(isOperational(), "Contract is currently not operational");
_;
}
modifier onlyAdmin() {
require(
hasRole(consortium.settings().ADMIN_ROLE(), msg.sender),
"Caller is not Admin"
);
_;
}
modifier onlyDelegate() {
require(
hasRole(consortium.settings().DELEGATE_ROLE(), msg.sender),
"Caller is not Delegate"
);
_;
}
modifier onlyConsortiumAirline() {
require(
consortium.isConsortiumAffiliate(msg.sender),
"Caller is not a consortium Airline"
);
_;
}
modifier onlyOracle() {
require(
hasRole(consortium.settings().ORACLE_ROLE(), msg.sender),
"Caller is not a registered Oracle"
);
_;
}
modifier onlyOracleFee() {
require(
msg.value == consortium.settings().ORACLE_MEMBERSHIP_FEE(),
"Unexpected membership fee"
);
_;
}
modifier onlyTrustedOracle(uint8 index) {
require(
(oracles[msg.sender].indexes[0] == index) ||
(oracles[msg.sender].indexes[1] == index) ||
(oracles[msg.sender].indexes[2] == index),
"Index does not match oracle request"
);
_;
}
modifier onlyValidFlightKey(bytes32 key) {
require(flights[key].isRegistered, "Invalid flight key");
_;
}
modifier onlyValidFlight(bytes32 key) {
require(flights[key].isRegistered, "Invalid flight");
_;
}
modifier onlyOpenResponse(uint8 index, bytes32 flightKey) {
bytes32 key = _getResponseKey(index, flightKey);
require(
oracleResponses[key].isOpen,
"Flight or timestamp do not match oracle request"
);
_;
}
/**
* @dev Constructor.
*/
constructor(address _consortiumAlliance) public {
consortium = ConsortiumAlliance(_consortiumAlliance);
_setupRole(consortium.settings().ADMIN_ROLE(), msg.sender);
emit LogAdminRegistered(msg.sender);
}
function isOperational() public view returns (bool) {
return consortium.isOperational();
}
function isAdmin(address _address)
public
view
onlyOperational
returns (bool)
{
return hasRole(consortium.settings().ADMIN_ROLE(), _address);
}
/**
* @dev Register a future flight for insuring.
*/
function registerFlight(bytes32 hexcode, uint256 timestamp)
external
onlyOperational
onlyConsortiumAirline
returns (bytes32)
{
address airline = msg.sender;
bytes32 key = _getFlightKey(airline, hexcode, timestamp);
flights[key] = Flight({
isRegistered: true,
airline: airline,
status: FlightStatus.UNKNOWN,
updatedTimestamp: timestamp
});
flightKeys.push(key);
emit LogFlightRegistered(key, airline, hexcode, timestamp);
return key;
}
/**
* @dev Register a new flight insurance.
*/
function registerFlightInsurance(bytes32 flightKey)
external
payable
onlyValidFlightKey(flightKey)
onlyOperational
returns (bytes32)
{
bytes32 insuranceKey = consortium.depositInsurance.value(msg.value)(
msg.sender
);
flightInsurances[flightKey].push(insuranceKey);
emit LogFlightInsuranceRegistered(insuranceKey, flightKey, msg.sender);
return insuranceKey;
}
/**
* @dev Register a new Oracle.
*/
function registerOracle() external payable onlyOracleFee {
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: _generateIndexes(msg.sender)
});
_setupRole(consortium.settings().ORACLE_ROLE(), msg.sender);
emit LogOracleRegistered(msg.sender);
}
function getMyIndexes() external view onlyOracle returns (uint8[3] memory) {
return oracles[msg.sender].indexes;
}
/**
* @dev Requests flight information to Oracles.
*/
function requestFlightStatus(bytes32 flightKey) external onlyOperational {
uint8 index = _getRandomIndex(msg.sender);
bytes32 responseKey = _getResponseKey(index, flightKey);
oracleResponses[responseKey] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit LogFlightStatusRequested(flightKey, responseKey, index);
}
/**
* @dev Called by Oracles when a response is available to an outstanding request
* For the response to be accepted, there must be a pending request that is open
* and matches one of the three Indexes randomly assigned to the oracle at the
* time of registration (i.e. only trusted oracles).
*/
function submitOracleResponse(
uint8 index,
bytes32 flightKey,
uint8 statusCode
) external onlyTrustedOracle(index) onlyOpenResponse(index, flightKey) {
bytes32 responseKey = _getResponseKey(index, flightKey);
oracleResponses[responseKey].responses[statusCode].push(msg.sender);
emit LogOracleReport(msg.sender, flightKey, FlightStatus(statusCode));
if (
oracleResponses[responseKey].responses[statusCode].length >=
consortium.settings().ORACLE_CONSENSUS_RESPONSES()
) {
emit LogFlightStatusResolved(flightKey, FlightStatus(statusCode));
_processFlightStatus(responseKey, flightKey, uint8(statusCode));
}
}
/**
* @dev Called after oracles have reached consensus on flight status.
*/
function _processFlightStatus(
bytes32 responseKey,
bytes32 flightKey,
uint8 statusCode
) internal onlyValidFlight(flightKey) {
FlightStatus status = FlightStatus(statusCode);
require(
status != FlightStatus.UNKNOWN,
"Unknown FlightStatus cannot be processed"
);
require(
oracleResponses[responseKey].isOpen,
"This flight status request has been resolved already"
);
flights[flightKey].status = status;
oracleResponses[responseKey].isOpen = false;
if (flights[flightKey].status == FlightStatus.LATE_AIRLINE) {
_creditInsuree(flightKey);
} else {
_creditConsortium(flightKey);
}
emit LogFlightStatusProcessed(flightKey);
}
/**
* @dev Credits insurance deposits and premiums to the insurees of
* a flight key by transfering the total amount to a escrow account.
*
*/
function _creditInsuree(bytes32 flight) internal {
for (uint256 i = 0; i < flightInsurances[flight].length; i++) {
bytes32 key = flightInsurances[flight][i];
consortium.creditInsuree(key);
emit LogInsureeCredited(flight, key);
}
}
/**
* @dev Credits the insurance deposits of a flight key to the Consortium.
*/
function _creditConsortium(bytes32 flight) internal {
for (uint256 i = 0; i < flightInsurances[flight].length; i++) {
bytes32 key = flightInsurances[flight][i];
consortium.creditConsortium(key);
emit LogConsortiumCredited(flight, key);
}
}
// --------------- MATH ---------------------------------------------------
function _getFlightKey(
address airline,
bytes32 flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function _getResponseKey(uint8 index, bytes32 flightKey)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(index, flightKey));
}
function _generateIndexes(address account)
internal
returns (uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = _getRandomIndex(account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = _getRandomIndex(account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = _getRandomIndex(account);
}
return indexes;
}
function _getRandomIndex(address account) internal returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number
uint8 random = uint8(
uint256(
keccak256(
abi.encodePacked(blockhash(block.number - nonce++), account)
)
) % maxValue
);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for the last 256 blocks
}
return random;
}
}
|
Requests flight information to Oracles./
|
function requestFlightStatus(bytes32 flightKey) external onlyOperational {
uint8 index = _getRandomIndex(msg.sender);
bytes32 responseKey = _getResponseKey(index, flightKey);
oracleResponses[responseKey] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit LogFlightStatusRequested(flightKey, responseKey, index);
}
| 13,086,773 |
./full_match/4/0x71BBe2d203dc57e6B1877CD336b74ccb3384a097/sources/contracts/Koiboi.sol
|
this is overriding an empty function in ERC721.sol It is also internal. Use tokenURI for the public external
|
function _baseURI() internal view virtual override returns (string memory) {
return _current_baseURI;
}
| 765,694 |
pragma solidity ^0.5.9;
import "./DelightBuildingManagerInterface.sol";
import "./DelightManager.sol";
import "./DelightArmyManager.sol";
import "./DelightItemManager.sol";
import "./Util/SafeMath.sol";
contract DelightBuildingManager is DelightBuildingManagerInterface, DelightManager {
using SafeMath for uint;
// Delight army manager
// Delight 부대 관리자
DelightArmyManager private armyManager;
// Delight item manager
// Delight 아이템 관리자
DelightItemManager private itemManager;
function setDelightArmyManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(address(armyManager) == address(0));
armyManager = DelightArmyManager(addr);
}
function setDelightItemManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(address(itemManager) == address(0));
itemManager = DelightItemManager(addr);
}
// Executes only if the sender is Delight.
// Sender가 Delight일때만 실행
modifier onlyDelight() {
require(
msg.sender == delight ||
msg.sender == address(armyManager) ||
msg.sender == address(itemManager)
);
_;
}
Building[] private buildings;
constructor(
DelightInfoInterface info,
DelightResource wood,
DelightResource stone,
DelightResource iron,
DelightResource ducat
) DelightManager(info, wood, stone, iron, ducat) public {
// Address 0 is not used.
// 0번지는 사용하지 않습니다.
buildings.push(Building({
kind : 99,
level : 0,
col : COL_RANGE,
row : ROW_RANGE,
owner : address(0),
buildTime : 0
}));
}
mapping(uint => mapping(uint => uint)) private positionToBuildingId;
mapping(address => uint[]) private ownerToHQIds;
// Returns the total number of buildings.
// 건물의 총 개수를 반환합니다.
function getBuildingCount() view external returns (uint) {
return buildings.length;
}
// Returns the information of a building.
// 건물의 정보를 반환합니다.
function getBuildingInfo(uint buildingId) view external returns (
uint kind,
uint level,
uint col,
uint row,
address owner,
uint buildTime
) {
Building memory building = buildings[buildingId];
return (
building.kind,
building.level,
building.col,
building.row,
building.owner,
building.buildTime
);
}
// Returns the IDs of the buildings located on a specific tile.
// 특정 위치의 건물 ID를 반환합니다.
function getPositionBuildingId(uint col, uint row) view external returns (uint) {
return positionToBuildingId[col][row];
}
// Returns the owners of the buildings located on a specific tile.
// 특정 위치의 건물의 주인을 반환합니다.
function getPositionBuildingOwner(uint col, uint row) view external returns (address) {
return buildings[positionToBuildingId[col][row]].owner;
}
// 소유주의 본부 ID들을 반환합니다.
function getOwnerHQIds(address owner) view external returns (uint[] memory) {
return ownerToHQIds[owner];
}
// 특정 위치의 건물의 버프 HP를 반환합니다.
function getBuildingBuffHP(uint col, uint row) view external returns (uint) {
uint buildingId = positionToBuildingId[col][row];
if (buildingId != 0) {
// 탑인 경우 버프 HP는 20
if (buildings[buildingId].kind == BUILDING_TOWER) {
return 20;
}
}
return 0;
}
// 특정 위치의 건물의 버프 데미지를 반환합니다.
function getBuildingBuffDamage(uint col, uint row) view external returns (uint) {
uint buildingId = positionToBuildingId[col][row];
if (buildingId != 0) {
// 탑인 경우 버프 데미지는 20
if (buildings[buildingId].kind == BUILDING_TOWER) {
return 20;
}
}
return 0;
}
// Builds a building.
// 건물을 짓습니다.
function build(address owner, uint kind, uint col, uint row) onlyDelight external {
// Checks the dimension.
// 범위를 체크합니다.
require(col < COL_RANGE && row < ROW_RANGE);
// There should be no building on the construction site.
// 필드에 건물이 존재하면 안됩니다.
require(positionToBuildingId[col][row] == 0);
address positionOwner = armyManager.getPositionOwner(col, row);
// There should be no enemy on the construction site.
// 필드에 적군이 존재하면 안됩니다.
require(positionOwner == address(0) || positionOwner == owner);
// Checks if a headquarter is near the construction site.
// 본부가 주변에 존재하는지 확인합니다.
bool existsHQAround = false;
for (uint i = 0; i < ownerToHQIds[owner].length; i += 1) {
Building memory building = buildings[ownerToHQIds[owner][i]];
uint hqCol = building.col;
uint hqRow = building.row;
if (
(col < hqCol ? hqCol - col : col - hqCol) +
(row < hqRow ? hqRow - row : row - hqRow) <= 3 + building.level.mul(2)
) {
existsHQAround = true;
break;
}
}
require(
// Checks if a headquarter is near the construction site.
// 본부가 주변에 존재하는지 확인합니다.
existsHQAround == true ||
// An HQ can be built even when there's no other HQ in the world, or where the builder's units are.
// 본부인 경우, 월드에 본부가 아예 없거나, 내 병사가 있는 위치에 지을 수 있습니다.
(kind == BUILDING_HQ && (ownerToHQIds[owner].length == 0 || positionOwner == owner))
);
// 만약 월드에 본부가 아예 없는 경우, 처음 짓는 곳 주변에 적군의 건물이 존재하면 안됩니다.
if (ownerToHQIds[owner].length == 0) {
for (uint i = (col <= 3 ? 0 : col - 3); i <= (col >= 96 ? 99 : col + 3); i += 1) {
for (uint j = (row <= 3 ? 0 : row - 3); j <= (row >= 96 ? 99 : row + 3); j += 1) {
require(positionToBuildingId[i][j] == 0 || buildings[positionToBuildingId[i][j]].owner == owner);
}
}
}
// Checks if there are enough resources to build the building.
// 건물을 짓는데 필요한 자원이 충분한지 확인합니다.
require(
wood.balanceOf(owner) >= info.getBuildingMaterialWood(kind) &&
stone.balanceOf(owner) >= info.getBuildingMaterialStone(kind) &&
iron.balanceOf(owner) >= info.getBuildingMaterialIron(kind) &&
ducat.balanceOf(owner) >= info.getBuildingMaterialDucat(kind)
);
uint buildingId = buildings.push(Building({
kind : kind,
level : 0,
col : col,
row : row,
owner : owner,
buildTime : now
})).sub(1);
positionToBuildingId[col][row] = buildingId;
if (kind == BUILDING_HQ) {
ownerToHQIds[owner].push(buildingId);
}
// Transfers the resources to Delight.
// 자원을 Delight로 이전합니다.
wood.transferFrom(owner, delight, info.getBuildingMaterialWood(kind));
stone.transferFrom(owner, delight, info.getBuildingMaterialStone(kind));
iron.transferFrom(owner, delight, info.getBuildingMaterialIron(kind));
ducat.transferFrom(owner, delight, info.getBuildingMaterialDucat(kind));
// Emits the event.
// 이벤트 발생
emit Build(buildingId);
}
// Upgrades an HQ.
// 본부를 업그레이드합니다.
function upgradeHQ(address owner, uint buildingId) onlyDelight external {
Building storage building = buildings[buildingId];
require(building.kind == BUILDING_HQ);
// Only the owner of the HQ can upgrade it.
// 건물 소유주만 업그레이드가 가능합니다.
require(building.owner == owner);
// The maximum level is 2.
// 최대 레벨은 2입니다. (0 ~ 2)
require(building.level < 2);
uint toLevel = building.level + 1;
// Checks if there are enough resources to upgrade the HQ.
// 본부를 업그레이드하는데 필요한 자원이 충분한지 확인합니다.
require(
wood.balanceOf(owner) >= info.getHQUpgradeMaterialWood(toLevel) &&
stone.balanceOf(owner) >= info.getHQUpgradeMaterialStone(toLevel) &&
iron.balanceOf(owner) >= info.getHQUpgradeMaterialIron(toLevel) &&
ducat.balanceOf(owner) >= info.getHQUpgradeMaterialDucat(toLevel)
);
// Transfers resources to Delight.
// 자원을 Delight로 이전합니다.
wood.transferFrom(owner, delight, info.getHQUpgradeMaterialWood(toLevel));
stone.transferFrom(owner, delight, info.getHQUpgradeMaterialStone(toLevel));
iron.transferFrom(owner, delight, info.getHQUpgradeMaterialIron(toLevel));
ducat.transferFrom(owner, delight, info.getHQUpgradeMaterialDucat(toLevel));
building.level = toLevel;
// Emits the event.
// 이벤트 발생
emit UpgradeHQ(buildingId);
}
// Creates an army from the building.
// 건물에서 부대를 생산합니다.
function createArmy(address owner, uint buildingId, uint unitCount) onlyDelight external {
Building memory building = buildings[buildingId];
// Only the owner of the building can create an army from it.
// 건물 소유주만 부대 생산이 가능합니다.
require(building.owner == owner);
uint unitKind;
// A hq creates knights.
// 본부의 경우 기사를 생산합니다.
if (building.kind == BUILDING_HQ) {
unitKind = UNIT_KNIGHT;
}
// A training center creates swordsmen.
// 훈련소의 경우 검병을 생산합니다.
else if (building.kind == BUILDING_TRAINING_CENTER) {
unitKind = UNIT_SWORDSMAN;
}
// An achery range creates archers.
// 사격소의 경우 궁수를 생산합니다.
else if (building.kind == BUILDING_ARCHERY_RANGE) {
unitKind = UNIT_ARCHER;
}
// A stable creates cavalry.
// 마굿간의 경우 기마병을 생산합니다.
else if (building.kind == BUILDING_STABLE) {
unitKind = UNIT_CAVALY;
}
else {
revert();
}
// Creates the army.
// 부대를 생산합니다.
armyManager.createArmy(owner, building.col, building.row, unitKind, unitCount);
}
// Destory the building on a specific tile.
// 특정 위치의 건물을 파괴합니다.
function destroyBuilding(uint col, uint row) onlyDelight external returns (
uint wood,
uint stone,
uint iron,
uint ducat
) {
uint buildingId = positionToBuildingId[col][row];
// The building must exist.
// 존재하는 건물이어야 합니다.
if (buildingId != 0) {
Building memory building = buildings[buildingId];
uint buildingKind = building.kind;
// If it's an HQ, it is removed from the HQ list.
// 본부인 경우, 본부 목록에서 제거합니다.
if (buildingKind == BUILDING_HQ) {
uint[] storage hqIds = ownerToHQIds[building.owner];
for (uint i = 0; i < hqIds.length - 1; i += 1) {
if (hqIds[i] == buildingId) {
for (; i < hqIds.length - 1; i += 1) {
hqIds[i] = hqIds[i + 1];
}
break;
}
}
hqIds.length -= 1;
// Returns the upgrade cost of the HQ.
// 본부 업그레이드 비용을 반환합니다.
for (uint i = 1; i <= building.level; i += 1) {
// Adds the returned material.
// 반환할 재료를 추가합니다.
wood = wood.add(info.getHQUpgradeMaterialWood(i));
stone = stone.add(info.getHQUpgradeMaterialStone(i));
iron = iron.add(info.getHQUpgradeMaterialIron(i));
ducat = ducat.add(info.getHQUpgradeMaterialDucat(i));
}
}
// Adds the returned material.
// 반환할 재료를 추가합니다.
wood = wood.add(info.getBuildingMaterialWood(buildingKind));
stone = stone.add(info.getBuildingMaterialStone(buildingKind));
iron = iron.add(info.getBuildingMaterialIron(buildingKind));
ducat = ducat.add(info.getBuildingMaterialDucat(buildingKind));
// Destroys the building.
// 건물을 파괴합니다.
delete buildings[buildingId];
delete positionToBuildingId[col][row];
// Emits the event.
// 이벤트 발생
emit DestroyBuilding(buildingId);
}
}
}
|
특정 위치의 건물의 버프 데미지를 반환합니다. 탑인 경우 버프 데미지는 20
|
function getBuildingBuffDamage(uint col, uint row) view external returns (uint) {
uint buildingId = positionToBuildingId[col][row];
if (buildingId != 0) {
if (buildings[buildingId].kind == BUILDING_TOWER) {
return 20;
}
}
return 0;
}
| 1,027,473 |
pragma solidity 0.5.17;
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 decimals() external view returns (uint256);
function name() external view returns (string memory);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function burn(uint amount) external;
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) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {codehash := extcodehash(account)}
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IController {
function vaults(address) external view returns (address);
function yfvInsuranceFund() external view returns (address);
function performanceReward() external view returns (address);
}
/*
A strategy must implement the following calls;
- deposit()
- withdraw(address) must exclude any tokens used in the yield - Controller role - withdraw should return to Controller
- withdraw(uint256) - Controller | Vault role - withdraw should always return to vault
- withdrawAll() - Controller | Vault role - withdraw should always return to vault
- balanceOf()
Where possible, strategies must remain as immutable as possible, instead of updating variables, we update the contract by linking it in the controller
*/
interface IStandardFarmingPool {
function withdraw(uint256) external;
function getReward() external;
function stake(uint256) external;
function balanceOf(address) external view returns (uint256);
function exit() external;
function earned(address) external view returns (uint256);
}
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
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 swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
interface IVault {
function make_profit(uint256 amount) external;
}
contract YFVStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public pool;
address public output;
string public getName;
address constant public yfv = address(0x45f24BaEef268BB6d63AEe5129015d69702BCDfa);
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uint256 public performanceFee = 250; // 2.5%
uint256 public insuranceFee = 100; // 1%
uint256 public burnFee = 0; // 0%
uint256 public gasFee = 100; // 1%
uint256 public constant FEE_DENOMINATOR = 10000;
address public governance;
address public controller;
address public want;
address[] public swapRouting;
constructor(address _controller, address _output, address _pool, address _want) public {
require(_controller != address(0), "!_controller");
require(_output != address(0), "!_output");
require(_pool != address(0), "!_pool");
require(_want != address(0), "!_want");
governance = tx.origin;
controller = _controller;
output = _output;
pool = _pool;
want = _want;
getName = string(
abi.encodePacked("yfv:Strategy:",
abi.encodePacked(IERC20(want).name(),
abi.encodePacked(":", IERC20(output).name())
)
));
init();
// output -> weth -> yfv
swapRouting = [output, weth, yfv];
}
function deposit() external {
IERC20(want).safeApprove(pool, 0);
IERC20(want).safeApprove(pool, IERC20(want).balanceOf(address(this)));
IStandardFarmingPool(pool).stake(IERC20(want).balanceOf(address(this)));
}
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
require(want != address(_asset), "want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint256 _amount) external {
require(msg.sender == controller, "!controller");
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
uint256 _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
IERC20(want).safeTransfer(_vault, _amount);
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() public returns (uint256 balance) {
require(msg.sender == controller || msg.sender == governance, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault");
// additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
IStandardFarmingPool(pool).exit();
}
function init() public {
IERC20(output).safeApprove(unirouter, uint256(- 1));
}
// to switch to another pool
function setNewPool(address _output, address _pool) public {
require(msg.sender == governance, "!governance");
require(_output != address(0), "!_output");
require(_pool != address(0), "!_pool");
harvest();
withdrawAll();
output = _output;
pool = _pool;
getName = string(
abi.encodePacked("yfv:Strategy:",
abi.encodePacked(IERC20(want).name(),
abi.encodePacked(":", IERC20(output).name())
)
));
}
function harvest() public {
require(!Address.isContract(msg.sender), "!contract");
IStandardFarmingPool(pool).getReward();
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
swap2yfv();
uint256 b = IERC20(yfv).balanceOf(address(this));
if (performanceFee > 0) {
uint256 _performanceFee = b.mul(performanceFee).div(FEE_DENOMINATOR);
IERC20(yfv).safeTransfer(IController(controller).performanceReward(), _performanceFee);
}
if (insuranceFee > 0) {
uint256 _insuranceFee = b.mul(insuranceFee).div(FEE_DENOMINATOR);
IERC20(yfv).safeTransfer(IController(controller).yfvInsuranceFund(), _insuranceFee);
}
if (burnFee > 0) {
uint256 _burnFee = b.mul(burnFee).div(FEE_DENOMINATOR);
IERC20(yfv).burn(_burnFee);
}
if (gasFee > 0) {
uint256 _gasFee = b.mul(gasFee).div(FEE_DENOMINATOR);
IERC20(yfv).safeTransfer(msg.sender, _gasFee);
}
IERC20(yfv).safeApprove(_vault, 0);
IERC20(yfv).safeApprove(_vault, IERC20(yfv).balanceOf(address(this)));
IVault(_vault).make_profit(IERC20(yfv).balanceOf(address(this)));
}
function swap2yfv() internal {
// path: output -> eth -> yfv
// swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline)
IUniswapRouter(unirouter).swapExactTokensForTokens(IERC20(output).balanceOf(address(this)), 1, swapRouting, address(this), now.add(1800));
}
function _withdrawSome(uint256 _amount) internal returns (uint256) {
IStandardFarmingPool(pool).withdraw(_amount);
return _amount;
}
function balanceOf() public view returns (uint256) {
return IERC20(want).balanceOf(address(this)).add(IStandardFarmingPool(pool).balanceOf(address(this)));
}
function balanceOfPendingReward() public view returns (uint256){
return IStandardFarmingPool(pool).earned(address(this));
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
function setPerformanceFee(uint256 _performanceFee) public {
require(msg.sender == governance, "!governance");
require(_performanceFee <= 2000, "_performanceFee should be not over 20%");
performanceFee = _performanceFee;
}
function setInsuranceFee(uint256 _insuranceFee) public {
require(msg.sender == governance, "!governance");
require(_insuranceFee <= 1000, "_insuranceFee should be not over 10%");
insuranceFee = _insuranceFee;
}
function setBurnFee(uint256 _burnFee) public {
require(msg.sender == governance, "!governance");
require(_burnFee <= 500, "_burnFee should be not over 5%");
burnFee = _burnFee;
}
function setGasFee(uint256 _gasFee) public {
require(msg.sender == governance, "!governance");
require(_gasFee <= 500, "_gasFee should be not over 5%");
gasFee = _gasFee;
}
function setSwapRouting(address[] memory _path) public {
require(msg.sender == governance, "!governance");
require(_path.length >= 2, "_path.length is less than 2");
swapRouting = _path;
}
}
|
Withdraw partial funds, normally used with a vault withdrawal
|
function withdraw(uint256 _amount) external {
require(msg.sender == controller, "!controller");
address _vault = IController(controller).vaults(address(want));
uint256 _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
IERC20(want).safeTransfer(_vault, _amount);
}
| 5,377,435 |
pragma solidity ^0.8.1;
// SPDX-License-Identifier: GPL-3.0-only
// importing latest version, rather than a commit-specific version, while I'm developing in parallel.
// a particular commit should be set once this get concretized.
import "https://github.com/swaldman/open-first-price-auction/blob/main/src/main/solidity/OpenFirstPriceAuctioneerUInt256.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/74e03de7604ca99c2f8e476476a6dc362779c356/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
contract TweetMarket is ERC721Enumerable, OpenFirstPriceAuctioneerUInt256 {
address public owner;
string public twitterUser;
string private _name;
string private _symbol;
// we divide initializtaion into a default no-arg constructor and an init(...) funtion for easy proxying.
constructor() ERC721("SHADOWED","SHADOWED") {}
function init(string memory _twitterUser) public {
require( owner != address(0), "Once init() has been called, it is initialized and owned and cannot be called again." );
require(bytes(_twitterUser)[0] != 0x40, "Don't prepend @ to Twitter username." );
_name = concat("Tweets-@", twitterUser);
_symbol = concat("TWT-@", twitterUser );
owner = msg.sender;
twitterUser = _twitterUser;
}
// override name and symbol since we require them to be set in init() rather than in a constructor
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
// override OpenFirstPriceAuctioneerUInt256 abstracts
function keyOwner( uint256 _key ) internal override view returns(address) {
return ownerOf( _key );
}
// nothing to do, since we have in-auction status of keys in parent class
function handleAuctionStarted( OpenFirstPriceAuction, address, uint256 ) internal override {}
// Transfer ownership here!!!
function handleAuctionCompleted( OpenFirstPriceAuction auction, address seller, address winner, uint256 key, uint256 /*winningBid*/ ) internal override {
_safeTransfer( seller, winner, key, abi.encodePacked(address(auction)) );
}
// nothing to do
function handleAuctionAborted( OpenFirstPriceAuction, address, uint256 ) internal override {}
modifier onlyOwner {
require( msg.sender == owner, "Function can only be called by owner." );
_;
}
function claim( uint256 _status ) public onlyOwner {
_mint( owner, _status );
}
function safeClaim( uint256 _status, bytes memory _data ) public onlyOwner {
_safeMint( owner, _status, _data );
}
function safeClaim( uint256 _status ) public onlyOwner {
_safeMint( owner, _status );
}
function updateTwitterUserName( string memory _twitterUser ) public onlyOwner {
require(bytes(_twitterUser)[0] != 0x40, "Don't prepend @ to Twitter username." );
twitterUser = _twitterUser;
}
function _baseURI() internal view override returns (string memory) {
return concat(concat("https://twitter.com/", twitterUser), "status/");
}
// see https://eattheblocks.com/how-to-manipulate-strings-in-solidity/
function concat( string memory a, string memory b ) internal pure returns(string memory) {
return string(abi.encodePacked(a, b));
}
// prevent transfers of tokens mid-auction
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(address(keyToAuction[tokenId]) == address(0), "No transfers are permitted while a token is in an auction.");
}
}
|
see https:eattheblocks.com/how-to-manipulate-strings-in-solidity/
|
function concat( string memory a, string memory b ) internal pure returns(string memory) {
return string(abi.encodePacked(a, b));
}
| 12,853,166 |
./partial_match/1/0xae248D0dCC7503126744b510D9B6703F1CaC8870/sources/DoubleEndedQueue.sol
|
Return the item at a position in the queue given by `index`, with the first item at 0 and last item at `length(deque) - 1`. Reverts with `OutOfBounds` if the index is out of bounds./ int256(deque._begin) is a safe upcast
|
function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value) {
int128 idx = SafeCast.toInt128(int256(deque._begin) + SafeCast.toInt256(index));
if (idx >= deque._end) revert OutOfBounds();
return deque._data[idx];
}
| 3,723,193 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./interfaces/IBancorFormula.sol";
import "../utility/SafeMath.sol";
contract BancorFormula is IBancorFormula {
using SafeMath for uint256;
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
// Auto-generated via 'PrintIntScalingFactors.py'
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
// Auto-generated via 'PrintLn2ScalingFactors.py'
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
// Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
// Auto-generated via 'PrintLambertFactors.py'
uint256 private constant LAMBERT_CONV_RADIUS = 0x002f16ac6c59de6f8d5d6f63c1482a7c86;
uint256 private constant LAMBERT_POS2_SAMPLE = 0x0003060c183060c183060c183060c18306;
uint256 private constant LAMBERT_POS2_MAXVAL = 0x01af16ac6c59de6f8d5d6f63c1482a7c80;
uint256 private constant LAMBERT_POS3_MAXVAL = 0x6b22d43e72c326539cceeef8bb48f255ff;
// Auto-generated via 'PrintWeightFactors.py'
uint256 private constant MAX_UNF_WEIGHT = 0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9;
// Auto-generated via 'PrintMaxExpArray.py'
uint256[128] private maxExpArray;
function initMaxExpArray() private {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
// Auto-generated via 'PrintLambertArray.py'
uint256[128] private lambertArray;
function initLambertArray() private {
lambertArray[ 0] = 0x60e393c68d20b1bd09deaabc0373b9c5;
lambertArray[ 1] = 0x5f8f46e4854120989ed94719fb4c2011;
lambertArray[ 2] = 0x5e479ebb9129fb1b7e72a648f992b606;
lambertArray[ 3] = 0x5d0bd23fe42dfedde2e9586be12b85fe;
lambertArray[ 4] = 0x5bdb29ddee979308ddfca81aeeb8095a;
lambertArray[ 5] = 0x5ab4fd8a260d2c7e2c0d2afcf0009dad;
lambertArray[ 6] = 0x5998b31359a55d48724c65cf09001221;
lambertArray[ 7] = 0x5885bcad2b322dfc43e8860f9c018cf5;
lambertArray[ 8] = 0x577b97aa1fe222bb452fdf111b1f0be2;
lambertArray[ 9] = 0x5679cb5e3575632e5baa27e2b949f704;
lambertArray[ 10] = 0x557fe8241b3a31c83c732f1cdff4a1c5;
lambertArray[ 11] = 0x548d868026504875d6e59bbe95fc2a6b;
lambertArray[ 12] = 0x53a2465ce347cf34d05a867c17dd3088;
lambertArray[ 13] = 0x52bdce5dcd4faed59c7f5511cf8f8acc;
lambertArray[ 14] = 0x51dfcb453c07f8da817606e7885f7c3e;
lambertArray[ 15] = 0x5107ef6b0a5a2be8f8ff15590daa3cce;
lambertArray[ 16] = 0x5035f241d6eae0cd7bacba119993de7b;
lambertArray[ 17] = 0x4f698fe90d5b53d532171e1210164c66;
lambertArray[ 18] = 0x4ea288ca297a0e6a09a0eee240e16c85;
lambertArray[ 19] = 0x4de0a13fdcf5d4213fc398ba6e3becde;
lambertArray[ 20] = 0x4d23a145eef91fec06b06140804c4808;
lambertArray[ 21] = 0x4c6b5430d4c1ee5526473db4ae0f11de;
lambertArray[ 22] = 0x4bb7886c240562eba11f4963a53b4240;
lambertArray[ 23] = 0x4b080f3f1cb491d2d521e0ea4583521e;
lambertArray[ 24] = 0x4a5cbc96a05589cb4d86be1db3168364;
lambertArray[ 25] = 0x49b566d40243517658d78c33162d6ece;
lambertArray[ 26] = 0x4911e6a02e5507a30f947383fd9a3276;
lambertArray[ 27] = 0x487216c2b31be4adc41db8a8d5cc0c88;
lambertArray[ 28] = 0x47d5d3fc4a7a1b188cd3d788b5c5e9fc;
lambertArray[ 29] = 0x473cfce4871a2c40bc4f9e1c32b955d0;
lambertArray[ 30] = 0x46a771ca578ab878485810e285e31c67;
lambertArray[ 31] = 0x4615149718aed4c258c373dc676aa72d;
lambertArray[ 32] = 0x4585c8b3f8fe489c6e1833ca47871384;
lambertArray[ 33] = 0x44f972f174e41e5efb7e9d63c29ce735;
lambertArray[ 34] = 0x446ff970ba86d8b00beb05ecebf3c4dc;
lambertArray[ 35] = 0x43e9438ec88971812d6f198b5ccaad96;
lambertArray[ 36] = 0x436539d11ff7bea657aeddb394e809ef;
lambertArray[ 37] = 0x42e3c5d3e5a913401d86f66db5d81c2c;
lambertArray[ 38] = 0x4264d2395303070ea726cbe98df62174;
lambertArray[ 39] = 0x41e84a9a593bb7194c3a6349ecae4eea;
lambertArray[ 40] = 0x416e1b785d13eba07a08f3f18876a5ab;
lambertArray[ 41] = 0x40f6322ff389d423ba9dd7e7e7b7e809;
lambertArray[ 42] = 0x40807cec8a466880ecf4184545d240a4;
lambertArray[ 43] = 0x400cea9ce88a8d3ae668e8ea0d9bf07f;
lambertArray[ 44] = 0x3f9b6ae8772d4c55091e0ed7dfea0ac1;
lambertArray[ 45] = 0x3f2bee253fd84594f54bcaafac383a13;
lambertArray[ 46] = 0x3ebe654e95208bb9210c575c081c5958;
lambertArray[ 47] = 0x3e52c1fc5665635b78ce1f05ad53c086;
lambertArray[ 48] = 0x3de8f65ac388101ddf718a6f5c1eff65;
lambertArray[ 49] = 0x3d80f522d59bd0b328ca012df4cd2d49;
lambertArray[ 50] = 0x3d1ab193129ea72b23648a161163a85a;
lambertArray[ 51] = 0x3cb61f68d32576c135b95cfb53f76d75;
lambertArray[ 52] = 0x3c5332d9f1aae851a3619e77e4cc8473;
lambertArray[ 53] = 0x3bf1e08edbe2aa109e1525f65759ef73;
lambertArray[ 54] = 0x3b921d9cff13fa2c197746a3dfc4918f;
lambertArray[ 55] = 0x3b33df818910bfc1a5aefb8f63ae2ac4;
lambertArray[ 56] = 0x3ad71c1c77e34fa32a9f184967eccbf6;
lambertArray[ 57] = 0x3a7bc9abf2c5bb53e2f7384a8a16521a;
lambertArray[ 58] = 0x3a21dec7e76369783a68a0c6385a1c57;
lambertArray[ 59] = 0x39c9525de6c9cdf7c1c157ca4a7a6ee3;
lambertArray[ 60] = 0x39721bad3dc85d1240ff0190e0adaac3;
lambertArray[ 61] = 0x391c324344d3248f0469eb28dd3d77e0;
lambertArray[ 62] = 0x38c78df7e3c796279fb4ff84394ab3da;
lambertArray[ 63] = 0x387426ea4638ae9aae08049d3554c20a;
lambertArray[ 64] = 0x3821f57dbd2763256c1a99bbd2051378;
lambertArray[ 65] = 0x37d0f256cb46a8c92ff62fbbef289698;
lambertArray[ 66] = 0x37811658591ffc7abdd1feaf3cef9b73;
lambertArray[ 67] = 0x37325aa10e9e82f7df0f380f7997154b;
lambertArray[ 68] = 0x36e4b888cfb408d873b9a80d439311c6;
lambertArray[ 69] = 0x3698299e59f4bb9de645fc9b08c64cca;
lambertArray[ 70] = 0x364ca7a5012cb603023b57dd3ebfd50d;
lambertArray[ 71] = 0x36022c928915b778ab1b06aaee7e61d4;
lambertArray[ 72] = 0x35b8b28d1a73dc27500ffe35559cc028;
lambertArray[ 73] = 0x357033e951fe250ec5eb4e60955132d7;
lambertArray[ 74] = 0x3528ab2867934e3a21b5412e4c4f8881;
lambertArray[ 75] = 0x34e212f66c55057f9676c80094a61d59;
lambertArray[ 76] = 0x349c66289e5b3c4b540c24f42fa4b9bb;
lambertArray[ 77] = 0x34579fbbd0c733a9c8d6af6b0f7d00f7;
lambertArray[ 78] = 0x3413bad2e712288b924b5882b5b369bf;
lambertArray[ 79] = 0x33d0b2b56286510ef730e213f71f12e9;
lambertArray[ 80] = 0x338e82ce00e2496262c64457535ba1a1;
lambertArray[ 81] = 0x334d26a96b373bb7c2f8ea1827f27a92;
lambertArray[ 82] = 0x330c99f4f4211469e00b3e18c31475ea;
lambertArray[ 83] = 0x32ccd87d6486094999c7d5e6f33237d8;
lambertArray[ 84] = 0x328dde2dd617b6665a2e8556f250c1af;
lambertArray[ 85] = 0x324fa70e9adc270f8262755af5a99af9;
lambertArray[ 86] = 0x32122f443110611ca51040f41fa6e1e3;
lambertArray[ 87] = 0x31d5730e42c0831482f0f1485c4263d8;
lambertArray[ 88] = 0x31996ec6b07b4a83421b5ebc4ab4e1f1;
lambertArray[ 89] = 0x315e1ee0a68ff46bb43ec2b85032e876;
lambertArray[ 90] = 0x31237fe7bc4deacf6775b9efa1a145f8;
lambertArray[ 91] = 0x30e98e7f1cc5a356e44627a6972ea2ff;
lambertArray[ 92] = 0x30b04760b8917ec74205a3002650ec05;
lambertArray[ 93] = 0x3077a75c803468e9132ce0cf3224241d;
lambertArray[ 94] = 0x303fab57a6a275c36f19cda9bace667a;
lambertArray[ 95] = 0x3008504beb8dcbd2cf3bc1f6d5a064f0;
lambertArray[ 96] = 0x2fd19346ed17dac61219ce0c2c5ac4b0;
lambertArray[ 97] = 0x2f9b7169808c324b5852fd3d54ba9714;
lambertArray[ 98] = 0x2f65e7e711cf4b064eea9c08cbdad574;
lambertArray[ 99] = 0x2f30f405093042ddff8a251b6bf6d103;
lambertArray[100] = 0x2efc931a3750f2e8bfe323edfe037574;
lambertArray[101] = 0x2ec8c28e46dbe56d98685278339400cb;
lambertArray[102] = 0x2e957fd933c3926d8a599b602379b851;
lambertArray[103] = 0x2e62c882c7c9ed4473412702f08ba0e5;
lambertArray[104] = 0x2e309a221c12ba361e3ed695167feee2;
lambertArray[105] = 0x2dfef25d1f865ae18dd07cfea4bcea10;
lambertArray[106] = 0x2dcdcee821cdc80decc02c44344aeb31;
lambertArray[107] = 0x2d9d2d8562b34944d0b201bb87260c83;
lambertArray[108] = 0x2d6d0c04a5b62a2c42636308669b729a;
lambertArray[109] = 0x2d3d6842c9a235517fc5a0332691528f;
lambertArray[110] = 0x2d0e402963fe1ea2834abc408c437c10;
lambertArray[111] = 0x2cdf91ae602647908aff975e4d6a2a8c;
lambertArray[112] = 0x2cb15ad3a1eb65f6d74a75da09a1b6c5;
lambertArray[113] = 0x2c8399a6ab8e9774d6fcff373d210727;
lambertArray[114] = 0x2c564c4046f64edba6883ca06bbc4535;
lambertArray[115] = 0x2c2970c431f952641e05cb493e23eed3;
lambertArray[116] = 0x2bfd0560cd9eb14563bc7c0732856c18;
lambertArray[117] = 0x2bd1084ed0332f7ff4150f9d0ef41a2c;
lambertArray[118] = 0x2ba577d0fa1628b76d040b12a82492fb;
lambertArray[119] = 0x2b7a5233cd21581e855e89dc2f1e8a92;
lambertArray[120] = 0x2b4f95cd46904d05d72bdcde337d9cc7;
lambertArray[121] = 0x2b2540fc9b4d9abba3faca6691914675;
lambertArray[122] = 0x2afb5229f68d0830d8be8adb0a0db70f;
lambertArray[123] = 0x2ad1c7c63a9b294c5bc73a3ba3ab7a2b;
lambertArray[124] = 0x2aa8a04ac3cbe1ee1c9c86361465dbb8;
lambertArray[125] = 0x2a7fda392d725a44a2c8aeb9ab35430d;
lambertArray[126] = 0x2a57741b18cde618717792b4faa216db;
lambertArray[127] = 0x2a2f6c81f5d84dd950a35626d6d5503a;
}
/**
* @dev should be executed after construction (too large for the constructor)
*/
function init() public {
initMaxExpArray();
initLambertArray();
}
/**
* @dev given a token supply, reserve balance, weight and a deposit amount (in the reserve token),
* calculates the target amount for a given conversion (in the main token)
*
* Formula:
* return = _supply * ((1 + _amount / _reserveBalance) ^ (_reserveWeight / 1000000) - 1)
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight, represented in ppm (1-1000000)
* @param _amount amount of reserve tokens to get the target amount for
*
* @return smart token amount
*/
function purchaseTargetAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT");
// special case for 0 deposit amount
if (_amount == 0)
return 0;
// special case if the weight = 100%
if (_reserveWeight == MAX_WEIGHT)
return _supply.mul(_amount) / _reserveBalance;
uint256 result;
uint8 precision;
uint256 baseN = _amount.add(_reserveBalance);
(result, precision) = power(baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
* @dev given a token supply, reserve balance, weight and a sell amount (in the main token),
* calculates the target amount for a given conversion (in the reserve token)
*
* Formula:
* return = _reserveBalance * (1 - (1 - _amount / _supply) ^ (1000000 / _reserveWeight))
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight, represented in ppm (1-1000000)
* @param _amount amount of smart tokens to get the target amount for
*
* @return reserve token amount
*/
function saleTargetAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT");
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 sell amount
if (_amount == 0)
return 0;
// special case for selling the entire supply
if (_amount == _supply)
return _reserveBalance;
// special case if the weight = 100%
if (_reserveWeight == MAX_WEIGHT)
return _reserveBalance.mul(_amount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _amount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveWeight);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given two reserve balances/weights and a sell amount (in the first reserve token),
* calculates the target amount for a conversion from the source reserve token to the target reserve token
*
* Formula:
* return = _targetReserveBalance * (1 - (_sourceReserveBalance / (_sourceReserveBalance + _amount)) ^ (_sourceReserveWeight / _targetReserveWeight))
*
* @param _sourceReserveBalance source reserve balance
* @param _sourceReserveWeight source reserve weight, represented in ppm (1-1000000)
* @param _targetReserveBalance target reserve balance
* @param _targetReserveWeight target reserve weight, represented in ppm (1-1000000)
* @param _amount source reserve amount
*
* @return target reserve amount
*/
function crossReserveTargetAmount(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_sourceReserveWeight > 0 && _sourceReserveWeight <= MAX_WEIGHT &&
_targetReserveWeight > 0 && _targetReserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT");
// special case for equal weights
if (_sourceReserveWeight == _targetReserveWeight)
return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _sourceReserveBalance.add(_amount);
(result, precision) = power(baseN, _sourceReserveBalance, _sourceReserveWeight, _targetReserveWeight);
uint256 temp1 = _targetReserveBalance.mul(result);
uint256 temp2 = _targetReserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given a smart token supply, reserve balance, reserve ratio and an amount of requested smart tokens,
* calculates the amount of reserve tokens required for purchasing the given amount of smart tokens
*
* Formula:
* return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio) - 1)
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount requested amount of smart tokens
*
* @return reserve token amount
*/
function fundCost(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO");
// special case for 0 amount
if (_amount == 0)
return 0;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
uint256 result;
uint8 precision;
uint256 baseN = _supply.add(_amount);
(result, precision) = power(baseN, _supply, MAX_WEIGHT, _reserveRatio);
uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1;
return temp - _reserveBalance;
}
/**
* @dev given a smart token supply, reserve balance, reserve ratio and an amount of reserve tokens to fund with,
* calculates the amount of smart tokens received for purchasing with the given amount of reserve tokens
*
* Formula:
* return = _supply * ((_amount / _reserveBalance + 1) ^ (_reserveRatio / MAX_WEIGHT) - 1)
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount amount of reserve tokens to fund with
*
* @return smart token amount
*/
function fundSupplyAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO");
// special case for 0 amount
if (_amount == 0)
return 0;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return _amount.mul(_supply) / _reserveBalance;
uint256 result;
uint8 precision;
uint256 baseN = _reserveBalance.add(_amount);
(result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
* @dev given a smart token supply, reserve balance, reserve ratio and an amount of smart tokens to liquidate,
* calculates the amount of reserve tokens received for selling the given amount of smart tokens
*
* Formula:
* return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio))
*
* @param _supply smart token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount amount of smart tokens to liquidate
*
* @return reserve token amount
*/
function liquidateReserveAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public override view returns (uint256)
{
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO");
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 amount
if (_amount == 0)
return 0;
// special case for liquidating the entire supply
if (_amount == _supply)
return _reserveBalance;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return _amount.mul(_reserveBalance) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _amount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveRatio);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev The arbitrage incentive is to convert to the point where the on-chain price is equal to the off-chain price.
* We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance.
* In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance.
*
* Formula input:
* - let t denote the primary reserve token staked balance
* - let s denote the primary reserve token balance
* - let r denote the secondary reserve token balance
* - let q denote the numerator of the rate between the tokens
* - let p denote the denominator of the rate between the tokens
* Where p primary tokens are equal to q secondary tokens
*
* Formula output:
* - compute x = W(t / r * q / p * log(s / t)) / log(s / t)
* - return x / (1 + x) as the weight of the primary reserve token
* - return 1 / (1 + x) as the weight of the secondary reserve token
* Where W is the Lambert W Function
*
* If the rate-provider provides the rates for a common unit, for example:
* - P = 2 ==> 2 primary reserve tokens = 1 ether
* - Q = 3 ==> 3 secondary reserve tokens = 1 ether
* Then you can simply use p = P and q = Q
*
* If the rate-provider provides the rates for a single unit, for example:
* - P = 2 ==> 1 primary reserve token = 2 ethers
* - Q = 3 ==> 1 secondary reserve token = 3 ethers
* Then you can simply use p = Q and q = P
*
* @param _primaryReserveStakedBalance the primary reserve token staked balance
* @param _primaryReserveBalance the primary reserve token balance
* @param _secondaryReserveBalance the secondary reserve token balance
* @param _reserveRateNumerator the numerator of the rate between the tokens
* @param _reserveRateDenominator the denominator of the rate between the tokens
*
* Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token
*
* @return the weight of the primary reserve token and the weight of the secondary reserve token, both in ppm (0-1000000)
*/
function balancedWeights(uint256 _primaryReserveStakedBalance,
uint256 _primaryReserveBalance,
uint256 _secondaryReserveBalance,
uint256 _reserveRateNumerator,
uint256 _reserveRateDenominator)
public override view returns (uint32, uint32)
{
if (_primaryReserveStakedBalance == _primaryReserveBalance)
require(_primaryReserveStakedBalance > 0 || _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
else
require(_primaryReserveStakedBalance > 0 && _primaryReserveBalance > 0 && _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_reserveRateNumerator > 0 && _reserveRateDenominator > 0, "ERR_INVALID_RESERVE_RATE");
uint256 tq = _primaryReserveStakedBalance.mul(_reserveRateNumerator);
uint256 rp = _secondaryReserveBalance.mul(_reserveRateDenominator);
if (_primaryReserveStakedBalance < _primaryReserveBalance)
return balancedWeightsByStake(_primaryReserveBalance, _primaryReserveStakedBalance, tq, rp, true);
if (_primaryReserveStakedBalance > _primaryReserveBalance)
return balancedWeightsByStake(_primaryReserveStakedBalance, _primaryReserveBalance, tq, rp, false);
return normalizedWeights(tq, rp);
}
/**
* @dev General Description:
* Determine a value of precision.
* Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
* Return the result along with the precision used.
*
* Detailed Description:
* Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
* The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
* The larger "precision" is, the more accurately this value represents the real value.
* However, the larger "precision" is, the more bits are required in order to store this value.
* And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
* This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
* Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
* This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
* This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
* Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = _baseN * FIXED_1 / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
}
else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = baseLog * _expN / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
}
else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1.
* This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
* @dev computes the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
* @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
* - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
* - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
require(false);
}
/**
* @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
* it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
* it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
* the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
* the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1
* Input range: FIXED_1 <= x <= OPT_LOG_MAX_VAL - 1
* Auto-generated via 'PrintFunctionOptimalLog.py'
* Detailed description:
* - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
* - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
* - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
* - The natural logarithm of the input is calculated by summing up the intermediate results above
* - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8
z = y = x - FIXED_1;
w = y * y / FIXED_1;
res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
* @dev computes e ^ (x / FIXED_1) * FIXED_1
* input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
* auto-generated via 'PrintFunctionOptimalExp.py'
* Detailed description:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
*/
function lowerStake(uint256 _x) internal view returns (uint256) {
if (_x <= LAMBERT_CONV_RADIUS)
return lambertPos1(_x);
if (_x <= LAMBERT_POS2_MAXVAL)
return lambertPos2(_x);
if (_x <= LAMBERT_POS3_MAXVAL)
return lambertPos3(_x);
require(false);
}
/**
* @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1
*/
function higherStake(uint256 _x) internal pure returns (uint256) {
if (_x <= LAMBERT_CONV_RADIUS)
return lambertNeg1(_x);
return FIXED_1 * FIXED_1 / _x;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: 1 <= x <= 1 / e * FIXED_1
* auto-generated via 'PrintFunctionLambertPos1.py'
*/
function lambertPos1(uint256 _x) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = (FIXED_1 - _x) * 0xde1bc4d19efcac82445da75b00000000; // x^(1-1) * (34! * 1^(1-1) / 1!) - x^(2-1) * (34! * 2^(2-1) / 2!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // sub x^(04-1) * (34! * 04^(04-1) / 04!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // sub x^(06-1) * (34! * 06^(06-1) / 06!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x000000002d207601f46a99b4112418400000000000; // sub x^(08-1) * (34! * 08^(08-1) / 08!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // sub x^(10-1) * (34! * 10^(10-1) / 10!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // sub x^(12-1) * (34! * 12^(12-1) / 12!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // sub x^(14-1) * (34! * 14^(14-1) / 14!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x000000bac08546b867cdaa20000000000000000000; // sub x^(16-1) * (34! * 16^(16-1) / 16!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x000004851d99f82060df265f3309b26f8200000000; // sub x^(18-1) * (34! * 18^(18-1) / 18!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // sub x^(20-1) * (34! * 20^(20-1) / 20!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // sub x^(22-1) * (34! * 22^(22-1) / 22!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // sub x^(24-1) * (34! * 24^(24-1) / 24!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // sub x^(26-1) * (34! * 26^(26-1) / 26!)
xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // sub x^(28-1) * (34! * 28^(28-1) / 28!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x053a044ebd984351493e1786af38d39a0800000000; // sub x^(30-1) * (34! * 30^(30-1) / 30!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!)
xi = (xi * _x) / FIXED_1; res -= xi * 0x231000000000000000000000000000000000000000; // sub x^(32-1) * (34! * 32^(32-1) / 32!)
xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!)
xi = (xi * _x) / FIXED_1; res -= xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // sub x^(34-1) * (34! * 34^(34-1) / 34!)
return res / 0xde1bc4d19efcac82445da75b00000000; // divide by 34!
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: LAMBERT_CONV_RADIUS + 1 <= x <= LAMBERT_POS2_MAXVAL
*/
function lambertPos2(uint256 _x) internal view returns (uint256) {
uint256 x = _x - LAMBERT_CONV_RADIUS - 1;
uint256 i = x / LAMBERT_POS2_SAMPLE;
uint256 a = LAMBERT_POS2_SAMPLE * i;
uint256 b = LAMBERT_POS2_SAMPLE * (i + 1);
uint256 c = lambertArray[i];
uint256 d = lambertArray[i + 1];
return (c * (b - x) + d * (x - a)) / LAMBERT_POS2_SAMPLE;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: LAMBERT_POS2_MAXVAL + 1 <= x <= LAMBERT_POS3_MAXVAL
*/
function lambertPos3(uint256 _x) internal pure returns (uint256) {
uint256 l1 = _x < OPT_LOG_MAX_VAL ? optimalLog(_x) : generalLog(_x);
uint256 l2 = l1 < OPT_LOG_MAX_VAL ? optimalLog(l1) : generalLog(l1);
return (l1 - l2 + l2 * FIXED_1 / l1) * FIXED_1 / _x;
}
/**
* @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1
* input range: 1 <= x <= 1 / e * FIXED_1
* auto-generated via 'PrintFunctionLambertNeg1.py'
*/
function lambertNeg1(uint256 _x) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // add x^(04-1) * (34! * 04^(04-1) / 04!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // add x^(06-1) * (34! * 06^(06-1) / 06!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000002d207601f46a99b4112418400000000000; // add x^(08-1) * (34! * 08^(08-1) / 08!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // add x^(10-1) * (34! * 10^(10-1) / 10!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // add x^(12-1) * (34! * 12^(12-1) / 12!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // add x^(14-1) * (34! * 14^(14-1) / 14!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000000bac08546b867cdaa20000000000000000000; // add x^(16-1) * (34! * 16^(16-1) / 16!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000004851d99f82060df265f3309b26f8200000000; // add x^(18-1) * (34! * 18^(18-1) / 18!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // add x^(20-1) * (34! * 20^(20-1) / 20!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // add x^(22-1) * (34! * 22^(22-1) / 22!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // add x^(24-1) * (34! * 24^(24-1) / 24!)
xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!)
xi = (xi * _x) / FIXED_1; res += xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // add x^(26-1) * (34! * 26^(26-1) / 26!)
xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!)
xi = (xi * _x) / FIXED_1; res += xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // add x^(28-1) * (34! * 28^(28-1) / 28!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!)
xi = (xi * _x) / FIXED_1; res += xi * 0x053a044ebd984351493e1786af38d39a0800000000; // add x^(30-1) * (34! * 30^(30-1) / 30!)
xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!)
xi = (xi * _x) / FIXED_1; res += xi * 0x231000000000000000000000000000000000000000; // add x^(32-1) * (34! * 32^(32-1) / 32!)
xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!)
xi = (xi * _x) / FIXED_1; res += xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // add x^(34-1) * (34! * 34^(34-1) / 34!)
return res / 0xde1bc4d19efcac82445da75b00000000 + _x + FIXED_1; // divide by 34! and then add x^(2-1) * (34! * 2^(2-1) / 2!) + x^(1-1) * (34! * 1^(1-1) / 1!)
}
/**
* @dev computes the weights based on "W(log(hi / lo) * tq / rp) * tq / rp", where "W" is a variation of the Lambert W function.
*/
function balancedWeightsByStake(uint256 _hi, uint256 _lo, uint256 _tq, uint256 _rp, bool _lowerStake) internal view returns (uint32, uint32) {
(_tq, _rp) = safeFactors(_tq, _rp);
uint256 f = _hi.mul(FIXED_1) / _lo;
uint256 g = f < OPT_LOG_MAX_VAL ? optimalLog(f) : generalLog(f);
uint256 x = g.mul(_tq) / _rp;
uint256 y = _lowerStake ? lowerStake(x) : higherStake(x);
return normalizedWeights(y.mul(_tq), _rp.mul(FIXED_1));
}
/**
* @dev reduces "a" and "b" while maintaining their ratio.
*/
function safeFactors(uint256 _a, uint256 _b) internal pure returns (uint256, uint256) {
if (_a <= FIXED_2 && _b <= FIXED_2)
return (_a, _b);
if (_a < FIXED_2)
return (_a * FIXED_2 / _b, FIXED_2);
if (_b < FIXED_2)
return (FIXED_2, _b * FIXED_2 / _a);
uint256 c = _a > _b ? _a : _b;
uint256 n = floorLog2(c / FIXED_1);
return (_a >> n, _b >> n);
}
/**
* @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)".
*/
function normalizedWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) {
if (_a <= _b)
return accurateWeights(_a, _b);
(uint32 y, uint32 x) = accurateWeights(_b, _a);
return (x, y);
}
/**
* @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)", assuming that "a <= b".
*/
function accurateWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) {
if (_a > MAX_UNF_WEIGHT) {
uint256 c = _a / (MAX_UNF_WEIGHT + 1) + 1;
_a /= c;
_b /= c;
}
uint256 x = roundDiv(_a * MAX_WEIGHT, _a.add(_b));
uint256 y = MAX_WEIGHT - x;
return (uint32(x), uint32(y));
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + _n % _d / (_d - _d / 2);
}
/**
* @dev deprecated, backward compatibility
*/
function calculatePurchaseReturn(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return purchaseTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateSaleReturn(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateCrossReserveReturn(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public view returns (uint256)
{
return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateCrossConnectorReturn(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public view returns (uint256)
{
return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateFundCost(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public view returns (uint256)
{
return fundCost(_supply, _reserveBalance, _reserveRatio, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateLiquidateReturn(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public view returns (uint256)
{
return liquidateReserveAmount(_supply, _reserveBalance, _reserveRatio, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function purchaseRate(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return purchaseTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function saleRate(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
public view returns (uint256)
{
return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function crossReserveRate(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public view returns (uint256)
{
return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function liquidateRate(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
public view returns (uint256)
{
return liquidateReserveAmount(_supply, _reserveBalance, _reserveRatio, _amount);
}
}
|
deprecated, backward compatibility/
|
function calculateCrossConnectorReturn(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
public view returns (uint256)
{
return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount);
}
| 1,786,851 |
pragma solidity ^0.4.11;
import "./Token/Token.sol";
import "./lib/ECVerify.sol";
/// @title Raiden MicroTransfer Channels Contract.
contract RaidenMicroTransferChannels {
/*
* Data structures
*/
address public owner;
address public token_address;
uint8 public challenge_period;
string constant prefix = "\x19Ethereum Signed Message:\n";
Token token;
mapping (bytes32 => Channel) channels;
mapping (bytes32 => ClosingRequest) closing_requests;
// 28 (deposit) + 4 (block no settlement)
struct Channel {
uint192 deposit; // mAX 2^192 == 2^6 * 2^18
uint32 open_block_number; // UNIQUE for participants to prevent replay of messages in later channels
}
struct ClosingRequest {
uint32 settle_block_number;
uint192 closing_balance;
}
/*
* Modifiers
*/
modifier isToken() {
require(msg.sender == token_address);
_;
}
/*
* Events
*/
event ChannelCreated(
address indexed _sender,
address indexed _receiver,
uint192 _deposit);
event ChannelToppedUp (
address indexed _sender,
address indexed _receiver,
uint32 indexed _open_block_number,
uint192 _added_deposit,
uint192 _deposit);
event ChannelCloseRequested(
address indexed _sender,
address indexed _receiver,
uint32 indexed _open_block_number,
uint192 _balance);
event ChannelSettled(
address indexed _sender,
address indexed _receiver,
uint32 indexed _open_block_number,
uint192 _balance);
event GasCost(
string _function_name,
uint _gaslimit,
uint _gas_remaining);
/*
* Constructor
*/
/// @dev Constructor for creating the Raiden microtransfer channels contract.
/// @param _token The address of the Token used by the channels.
/// @param _challenge_period A fixed number of blocks representing the challenge period after a sender requests the closing of the channel without the receiver's signature.
function RaidenMicroTransferChannels(address _token, uint8 _challenge_period) {
require(_token != 0x0);
require(_challenge_period > 0);
owner = msg.sender;
token_address = _token;
token = Token(_token);
challenge_period = _challenge_period;
}
/*
* Public helper functions (constant)
*/
/// @dev Returns the unique channel identifier used in the contract.
/// @param _sender The address that sends tokens.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @return Unique channel identifier.
function getKey(
address _sender,
address _receiver,
uint32 _open_block_number)
public
constant
returns (bytes32 data)
{
return sha3(_sender, _receiver, _open_block_number);
}
/// @dev Returns a hash of the balance message needed to be signed by the sender.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
/// @return Hash of the balance message.
function getBalanceMessage(
address _receiver,
uint32 _open_block_number,
uint192 _balance)
public
constant
returns (string)
{
string memory str = concat("Receiver: 0x", addressToString(_receiver));
str = concat(str, ", Balance: ");
str = concat(str, uintToString(uint256(_balance)));
str = concat(str, ", Channel ID: ");
str = concat(str, uintToString(uint256(_open_block_number)));
return str;
}
// 56014 gas cost
/// @dev Returns the sender address extracted from the balance proof.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
/// @param _balance_msg_sig The balance message signed by the sender or receiver.
/// @return Address of the balance proof signer.
function verifyBalanceProof(
address _receiver,
uint32 _open_block_number,
uint192 _balance,
bytes _balance_msg_sig)
public
constant
returns (address)
{
//GasCost('close verifyBalanceProof getBalanceMessage start', block.gaslimit, msg.gas);
// Create message which should be signed by sender
string memory message = getBalanceMessage(_receiver, _open_block_number, _balance);
//GasCost('close verifyBalanceProof getBalanceMessage end', block.gaslimit, msg.gas);
//GasCost('close verifyBalanceProof length start', block.gaslimit, msg.gas);
// 2446 gas cost
// TODO: improve length calc
uint message_length = bytes(message).length;
//GasCost('close verifyBalanceProof length end', block.gaslimit, msg.gas);
//GasCost('close verifyBalanceProof uintToString start', block.gaslimit, msg.gas);
string memory message_length_string = uintToString(message_length);
//GasCost('close verifyBalanceProof uintToString end', block.gaslimit, msg.gas);
//GasCost('close verifyBalanceProof concat start', block.gaslimit, msg.gas);
// Prefix the message
string memory prefixed_message = concat(prefix, message_length_string);
//GasCost('close verifyBalanceProof concat end', block.gaslimit, msg.gas);
prefixed_message = concat(prefixed_message, message);
// Hash the prefixed message string
bytes32 prefixed_message_hash = sha3(prefixed_message);
// Derive address from signature
address signer = ECVerify.ecverify(prefixed_message_hash, _balance_msg_sig);
return signer;
}
/*
* External functions
*/
/// @dev Calls createChannel, compatibility with ERC 223; msg.sender is Token contract.
/// @param _sender The address that sends the tokens.
/// @param _deposit The amount of tokens that the sender escrows.
/// @param _data Receiver address in bytes.
function tokenFallback(
address _sender,
uint256 _deposit,
bytes _data)
external
{
// Make sure we trust the token
require(msg.sender == token_address);
//GasCost('tokenFallback start0', block.gaslimit, msg.gas);
uint length = _data.length;
// createChannel - receiver address (20 bytes + padding = 32 bytes)
// topUp - receiver address (32 bytes) + open_block_number (4 bytes + padding = 32 bytes)
require(length == 20 || length == 24);
//GasCost('tokenFallback addressFromData start', block.gaslimit, msg.gas);
address receiver = addressFromData(_data);
//GasCost('tokenFallback addressFromData end', block.gaslimit, msg.gas);
if(length == 20) {
createChannelPrivate(_sender, receiver, uint192(_deposit));
}
else {
//GasCost('tokenFallback blockNumberFromData start', block.gaslimit, msg.gas);
uint32 open_block_number = blockNumberFromData(_data);
//GasCost('tokenFallback blockNumberFromData end', block.gaslimit, msg.gas);
topUpPrivate(_sender, receiver, open_block_number, uint192(_deposit));
}
//GasCost('tokenFallback end', block.gaslimit, msg.gas);
}
/// @dev Creates a new channel between a sender and a receiver and transfers the sender's token deposit to this contract, compatibility with ERC20 tokens.
/// @param _receiver The address that receives tokens.
/// @param _deposit The amount of tokens that the sender escrows.
function createChannelERC20(
address _receiver,
uint192 _deposit)
external
{
createChannelPrivate(msg.sender, _receiver, _deposit);
// transferFrom deposit from _sender to contract
// ! needs prior approval from user
require(token.transferFrom(msg.sender, address(this), _deposit));
}
// TODO (WIP) Funds channel with an additional deposit of tokens. ERC20 compatibility.
/// @dev Increase the sender's current deposit.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function topUpERC20(
address _receiver,
uint32 _open_block_number,
uint192 _added_deposit)
external
{
// transferFrom deposit from msg.sender to contract
// ! needs prior approval from user
require(token.transferFrom(msg.sender, address(this), _added_deposit));
topUpPrivate(msg.sender, _receiver, _open_block_number, _added_deposit);
}
/// @dev Function called when any of the parties wants to close the channel and settle; receiver needs a balance proof to immediately settle, sender triggers a challenge period.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
/// @param _balance_msg_sig The balance message signed by the sender.
function close(
address _receiver,
uint32 _open_block_number,
uint192 _balance,
bytes _balance_msg_sig)
external
{
require(_balance_msg_sig.length == 65);
//GasCost('close verifyBalanceProof start', block.gaslimit, msg.gas);
address sender = verifyBalanceProof(_receiver, _open_block_number, _balance, _balance_msg_sig);
//GasCost('close verifyBalanceProof end', block.gaslimit, msg.gas);
if(msg.sender == _receiver) {
settleChannel(sender, _receiver, _open_block_number, _balance);
}
else {
require(msg.sender == sender);
initChallengePeriod(_receiver, _open_block_number, _balance);
}
}
/// @dev Function called by the sender, when he has a closing signature from the receiver; channel is closed immediately.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
/// @param _balance_msg_sig The balance message signed by the sender.
/// @param _closing_sig The hash of the signed balance message, signed by the receiver.
function close(
address _receiver,
uint32 _open_block_number,
uint192 _balance,
bytes _balance_msg_sig,
bytes _closing_sig)
external
{
require(_balance_msg_sig.length == 65);
require(_closing_sig.length == 65);
//GasCost('close coop verifyBalanceProof start', block.gaslimit, msg.gas);
// derive address from signature
address receiver = verifyBalanceProof(_receiver, _open_block_number, _balance, _closing_sig);
//GasCost('close coop verifyBalanceProof start', block.gaslimit, msg.gas);
require(receiver == _receiver);
address sender = verifyBalanceProof(_receiver, _open_block_number, _balance, _balance_msg_sig);
require(msg.sender == sender);
settleChannel(sender, receiver, _open_block_number, _balance);
}
/// @dev Function for getting information about a channel.
/// @param _sender The address that sends tokens.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @return Channel information (unique_identifier, deposit, settle_block_number, closing_balance).
function getChannelInfo(
address _sender,
address _receiver,
uint32 _open_block_number)
external
constant
returns (bytes32, uint192, uint32, uint192)
{
bytes32 key = getKey(_sender, _receiver, _open_block_number);
require(channels[key].open_block_number != 0);
return (key, channels[key].deposit, closing_requests[key].settle_block_number, closing_requests[key].closing_balance);
}
/// @dev Function called by the sender after the challenge period has ended, in case the receiver has not closed the channel.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
function settle(
address _receiver,
uint32 _open_block_number)
external
{
bytes32 key = getKey(msg.sender, _receiver, _open_block_number);
require(closing_requests[key].settle_block_number != 0);
require(block.number > closing_requests[key].settle_block_number);
settleChannel(msg.sender, _receiver, _open_block_number, closing_requests[key].closing_balance);
}
/*
* Private functions
*/
/// @dev Creates a new channel between a sender and a receiver, only callable by the Token contract.
/// @param _sender The address that receives tokens.
/// @param _receiver The address that receives tokens.
/// @param _deposit The amount of tokens that the sender escrows.
function createChannelPrivate(
address _sender,
address _receiver,
uint192 _deposit)
private
{
//GasCost('createChannel start', block.gaslimit, msg.gas);
uint32 open_block_number = uint32(block.number);
// Create unique identifier from sender, receiver and current block number
bytes32 key = getKey(_sender, _receiver, open_block_number);
require(channels[key].deposit == 0);
require(channels[key].open_block_number == 0);
require(closing_requests[key].settle_block_number == 0);
// Store channel information
channels[key] = Channel({deposit: _deposit, open_block_number: open_block_number});
//GasCost('createChannel end', block.gaslimit, msg.gas);
ChannelCreated(_sender, _receiver, _deposit);
}
// TODO (WIP)
/// @dev Funds channel with an additional deposit of tokens, only callable by the Token contract.
/// @param _sender The address that sends tokens.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function topUpPrivate(
address _sender,
address _receiver,
uint32 _open_block_number,
uint192 _added_deposit)
private
{
//GasCost('topUp start', block.gaslimit, msg.gas);
require(_added_deposit != 0);
require(_open_block_number != 0);
bytes32 key = getKey(_sender, _receiver, _open_block_number);
require(channels[key].deposit != 0);
require(closing_requests[key].settle_block_number == 0);
channels[key].deposit += _added_deposit;
ChannelToppedUp(_sender, _receiver, _open_block_number, _added_deposit, channels[key].deposit);
//GasCost('topUp end', block.gaslimit, msg.gas);
}
/// @dev Sender starts the challenge period; this can only happend once.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function initChallengePeriod(
address _receiver,
uint32 _open_block_number,
uint192 _balance)
private
{
//GasCost('initChallengePeriod end', block.gaslimit, msg.gas);
bytes32 key = getKey(msg.sender, _receiver, _open_block_number);
require(closing_requests[key].settle_block_number == 0);
require(_balance <= channels[key].deposit);
// Mark channel as closed
closing_requests[key].settle_block_number = uint32(block.number) + challenge_period;
closing_requests[key].closing_balance = _balance;
ChannelCloseRequested(msg.sender, _receiver, _open_block_number, _balance);
//GasCost('initChallengePeriod end', block.gaslimit, msg.gas);
}
/// @dev Closes the channel and settles by transfering the balance to the receiver and the rest of the deposit back to the sender.
/// @param _sender The address that sends tokens.
/// @param _receiver The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function settleChannel(
address _sender,
address _receiver,
uint32 _open_block_number,
uint192 _balance)
private
{
//GasCost('settleChannel start', block.gaslimit, msg.gas);
bytes32 key = getKey(_sender, _receiver, _open_block_number);
Channel channel = channels[key];
// TODO delete this if we don't include open_block_number in the Channel struct
require(channel.open_block_number != 0);
require(_balance <= channel.deposit);
// send minimum of _balance and deposit to receiver
uint send_to_receiver = min(_balance, channel.deposit);
if(send_to_receiver > 0) {
//GasCost('settleChannel', block.gaslimit, msg.gas);
require(token.transfer(_receiver, send_to_receiver));
}
// send maximum of deposit - balance and 0 to sender
uint send_to_sender = max(channel.deposit - _balance, 0);
if(send_to_sender > 0) {
//GasCost('settleChannel', block.gaslimit, msg.gas);
require(token.transfer(_sender, send_to_sender));
}
assert(channel.deposit >= _balance);
// remove closed channel structures
delete channels[key];
delete closing_requests[key];
ChannelSettled(_sender, _receiver, _open_block_number, _balance);
//GasCost('settleChannel end', block.gaslimit, msg.gas);
}
/*
* Internal functions
*/
/// @dev Internal function for getting the maximum between two numbers.
/// @param a First number to compare.
/// @param b Second number to compare.
/// @return The maximum between the two provided numbers.
function max(uint192 a, uint192 b)
internal
constant
returns (uint)
{
if (a > b) return a;
else return b;
}
/// @dev Internal function for getting the minimum between two numbers.
/// @param a First number to compare.
/// @param b Second number to compare.
/// @return The minimum between the two provided numbers.
function min(uint192 a, uint192 b)
internal
constant
returns (uint)
{
if (a < b) return a;
else return b;
}
// 2656 gas cost
/// @dev Internal function for getting an address from tokenFallback data bytes.
/// @param b Bytes received.
/// @return Address resulted.
function addressFromData (
bytes b)
internal
constant
returns (address)
{
bytes20 addr;
assembly {
// Read address bytes
// Offset of 32 bytes, representing b.length
addr := mload(add(b, 0x20))
}
return address(addr);
}
// 2662 gas cost
/// @dev Internal function for getting the block number from tokenFallback data bytes.
/// @param b Bytes received.
/// @return Block number.
function blockNumberFromData(
bytes b)
internal
constant
returns (uint32)
{
bytes4 block_number;
assembly {
// Read block number bytes
// Offset of 32 bytes (b.length) + 20 bytes (address)
block_number := mload(add(b, 0x34))
}
return uint32(block_number);
}
function memcpy(
uint dest,
uint src,
uint len)
private
{
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
// 3813 gas cost
function concat(
string _self,
string _other)
internal
constant
returns (string)
{
uint self_len = bytes(_self).length;
uint other_len = bytes(_other).length;
uint self_ptr;
uint other_ptr;
assembly {
self_ptr := add(_self, 0x20)
other_ptr := add(_other, 0x20)
}
var ret = new string(self_len + other_len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self_ptr, self_len);
memcpy(retptr + self_len, other_ptr, other_len);
return ret;
}
/*function uintToBytes (
uint256 n)
internal
constant
returns (bytes32 b)
{
//b = new bytes(32);
assembly {
//mstore(add(b, 32), n)
b := mload(add(n, 32))
}
}
function uintToBytes32 (
uint256 n)
internal
constant
returns (bytes32 b)
{
assembly {
b := mload(add(n, 32))
}
}
function stringToBytes1(
string str)
internal
constant
returns (bytes)
{
return bytes(str);
}
function stringToBytes2(
string source)
internal
constant
returns (bytes result)
{
uint len = bytes(source).length;
result = new bytes(len);
assembly {
result := mload(add(source, len))
}
}*/
// 9613 gas
function uintToString(
uint v)
internal
constant
returns (string)
{
bytes32 ret;
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;
}
}
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(ret) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
function addressToString(
address x)
internal
constant
returns (string)
{
bytes memory str = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte b = byte(uint8(uint(x) / (2**(8*(19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
str[2*i] = char(hi);
str[2*i+1] = char(lo);
}
return string(str);
}
function char(byte b)
internal
constant
returns (byte c)
{
if (b < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
}
|
Function for getting information about a channel. _sender The address that sends tokens. _receiver The address that receives tokens. _open_block_number The block number at which a channel between the sender and receiver was created. return Channel information (unique_identifier, deposit, settle_block_number, closing_balance).
|
function getChannelInfo(
address _sender,
address _receiver,
uint32 _open_block_number)
external
constant
returns (bytes32, uint192, uint32, uint192)
{
bytes32 key = getKey(_sender, _receiver, _open_block_number);
require(channels[key].open_block_number != 0);
return (key, channels[key].deposit, closing_requests[key].settle_block_number, closing_requests[key].closing_balance);
}
| 12,973,262 |
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "./interfaces/IValidatorShare.sol";
import "./interfaces/INodeOperatorRegistry.sol";
import "./interfaces/IStakeManager.sol";
import "./interfaces/IPoLidoNFT.sol";
import "./interfaces/IFxStateRootTunnel.sol";
import "./interfaces/IStMATIC.sol";
contract StMATIC is
IStMATIC,
ERC20Upgradeable,
AccessControlUpgradeable,
PausableUpgradeable
{
event SubmitEvent(address indexed _from, uint256 indexed _amount);
event RequestWithdrawEvent(address indexed _from, uint256 indexed _amount);
event DistributeRewardsEvent(uint256 indexed _amount);
event WithdrawTotalDelegatedEvent(
address indexed _from,
uint256 indexed _amount
);
event DelegateEvent(
uint256 indexed _amountDelegated,
uint256 indexed _remainder
);
event ClaimTokensEvent(
address indexed _from,
uint256 indexed _id,
uint256 indexed _amountClaimed,
uint256 _amountBurned
);
event ClaimTotalDelegatedEvent(
address indexed _from,
uint256 indexed _amountClaimed
);
using SafeERC20Upgradeable for IERC20Upgradeable;
INodeOperatorRegistry public override nodeOperatorRegistry;
FeeDistribution public override entityFees;
IStakeManager public override stakeManager;
IPoLidoNFT public override poLidoNFT;
IFxStateRootTunnel public override fxStateRootTunnel;
string public override version;
address public override dao;
address public override insurance;
address public override token;
uint256 public override lastWithdrawnValidatorId;
uint256 public override totalBuffered;
uint256 public override delegationLowerBound;
uint256 public override rewardDistributionLowerBound;
uint256 public override reservedFunds;
uint256 public override submitThreshold;
bool public override submitHandler;
mapping(uint256 => RequestWithdraw) public override token2WithdrawRequest;
bytes32 public constant override DAO = keccak256("DAO");
RequestWithdraw[] public stMaticWithdrawRequest;
/**
* @param _nodeOperatorRegistry - Address of the node operator registry
* @param _token - Address of MATIC token on Ethereum Mainnet
* @param _dao - Address of the DAO
* @param _insurance - Address of the insurance
* @param _stakeManager - Address of the stake manager
* @param _poLidoNFT - Address of the stMATIC NFT
* @param _fxStateRootTunnel - Address of the FxStateRootTunnel
*/
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external override initializer {
__AccessControl_init();
__Pausable_init();
__ERC20_init("Staked MATIC", "stMATIC");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(DAO, _dao);
nodeOperatorRegistry = INodeOperatorRegistry(_nodeOperatorRegistry);
stakeManager = IStakeManager(_stakeManager);
poLidoNFT = IPoLidoNFT(_poLidoNFT);
fxStateRootTunnel = IFxStateRootTunnel(_fxStateRootTunnel);
dao = _dao;
token = _token;
insurance = _insurance;
entityFees = FeeDistribution(25, 50, 25);
submitThreshold = _submitThreshold;
submitHandler = true;
}
/**
* @dev Send funds to StMATIC contract and mints StMATIC to msg.sender
* @notice Requires that msg.sender has approved _amount of MATIC to this contract
* @param _amount - Amount of MATIC sent from msg.sender to this contract
* @return Amount of StMATIC shares generated
*/
function submit(uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
require(_amount > 0, "Invalid amount");
if (submitHandler) {
require(
_amount + getTotalPooledMatic() <= submitThreshold,
"Submit threshold reached"
);
}
IERC20Upgradeable(token).safeTransferFrom(
msg.sender,
address(this),
_amount
);
(
uint256 amountToMint,
uint256 totalShares,
uint256 totalPooledMatic
) = convertMaticToStMatic(_amount);
_mint(msg.sender, amountToMint);
totalBuffered += _amount;
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalShares + amountToMint, totalPooledMatic + _amount)
);
emit SubmitEvent(msg.sender, _amount);
return amountToMint;
}
/**
* @dev Stores users request to withdraw into a RequestWithdraw struct
* @param _amount - Amount of StMATIC that is requested to withdraw
*/
function requestWithdraw(uint256 _amount) external override whenNotPaused {
require(_amount > 0, "Invalid amount");
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
uint256 operatorInfosLength = operatorInfos.length;
uint256 tokenId;
(
uint256 totalAmount2WithdrawInMatic,
uint256 totalShares,
uint256 totalPooledMATIC
) = convertStMaticToMatic(_amount);
uint256 currentAmount2WithdrawInMatic = totalAmount2WithdrawInMatic;
uint256 totalDelegated = getTotalStakeAcrossAllValidators();
uint256 minValidatorBalance = _getMinValidatorBalance(operatorInfos);
uint256 allowedAmount2RequestFromValidators = 0;
if (totalDelegated != 0) {
require(
(totalDelegated + totalBuffered) >=
currentAmount2WithdrawInMatic +
minValidatorBalance *
operatorInfosLength,
"Too much to withdraw"
);
allowedAmount2RequestFromValidators =
totalDelegated -
minValidatorBalance *
operatorInfosLength;
} else {
require(
totalBuffered >= currentAmount2WithdrawInMatic,
"Too much to withdraw"
);
}
while (currentAmount2WithdrawInMatic != 0) {
tokenId = poLidoNFT.mint(msg.sender);
if (allowedAmount2RequestFromValidators != 0) {
if (lastWithdrawnValidatorId > operatorInfosLength - 1) {
lastWithdrawnValidatorId = 0;
}
address validatorShare = operatorInfos[lastWithdrawnValidatorId]
.validatorShare;
(uint256 validatorBalance, ) = IValidatorShare(validatorShare)
.getTotalStake(address(this));
if (validatorBalance <= minValidatorBalance) {
lastWithdrawnValidatorId++;
continue;
}
uint256 allowedAmount2Withdraw = validatorBalance -
minValidatorBalance;
uint256 amount2WithdrawFromValidator = (allowedAmount2Withdraw <=
currentAmount2WithdrawInMatic)
? allowedAmount2Withdraw
: currentAmount2WithdrawInMatic;
sellVoucher_new(
validatorShare,
amount2WithdrawFromValidator,
type(uint256).max
);
token2WithdrawRequest[tokenId] = RequestWithdraw(
0,
IValidatorShare(validatorShare).unbondNonces(address(this)),
stakeManager.epoch() + stakeManager.withdrawalDelay(),
validatorShare
);
allowedAmount2RequestFromValidators -= amount2WithdrawFromValidator;
currentAmount2WithdrawInMatic -= amount2WithdrawFromValidator;
lastWithdrawnValidatorId++;
} else {
token2WithdrawRequest[tokenId] = RequestWithdraw(
currentAmount2WithdrawInMatic,
0,
stakeManager.epoch() + stakeManager.withdrawalDelay(),
address(0)
);
reservedFunds += currentAmount2WithdrawInMatic;
currentAmount2WithdrawInMatic = 0;
}
}
_burn(msg.sender, _amount);
fxStateRootTunnel.sendMessageToChild(
abi.encode(
totalShares - _amount,
totalPooledMATIC - totalAmount2WithdrawInMatic
)
);
emit RequestWithdrawEvent(msg.sender, _amount);
}
/**
* @notice This will be included in the cron job
* @dev Delegates tokens to validator share contract
*/
function delegate() external override whenNotPaused {
require(
totalBuffered > delegationLowerBound + reservedFunds,
"Amount to delegate lower than minimum"
);
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(true, false);
uint256 operatorInfosLength = operatorInfos.length;
require(operatorInfosLength > 0, "No operator shares, cannot delegate");
uint256 availableAmountToDelegate = totalBuffered - reservedFunds;
uint256 maxDelegateLimitsSum;
uint256 remainder;
for (uint256 i = 0; i < operatorInfosLength; i++) {
maxDelegateLimitsSum += operatorInfos[i].maxDelegateLimit;
}
require(maxDelegateLimitsSum > 0, "maxDelegateLimitsSum=0");
uint256 totalToDelegatedAmount = maxDelegateLimitsSum <=
availableAmountToDelegate
? maxDelegateLimitsSum
: availableAmountToDelegate;
IERC20Upgradeable(token).safeApprove(address(stakeManager), 0);
IERC20Upgradeable(token).safeApprove(
address(stakeManager),
totalToDelegatedAmount
);
uint256 amountDelegated;
for (uint256 i = 0; i < operatorInfosLength; i++) {
uint256 amountToDelegatePerOperator = (operatorInfos[i]
.maxDelegateLimit * totalToDelegatedAmount) /
maxDelegateLimitsSum;
buyVoucher(
operatorInfos[i].validatorShare,
amountToDelegatePerOperator,
0
);
amountDelegated += amountToDelegatePerOperator;
}
remainder = availableAmountToDelegate - amountDelegated;
totalBuffered = remainder + reservedFunds;
emit DelegateEvent(amountDelegated, remainder);
}
/**
* @dev Claims tokens from validator share and sends them to the
* user if his request is in the userToWithdrawRequest
* @param _tokenId - Id of the token that wants to be claimed
*/
function claimTokens(uint256 _tokenId) external override whenNotPaused {
require(poLidoNFT.isApprovedOrOwner(msg.sender, _tokenId), "Not owner");
RequestWithdraw storage usersRequest = token2WithdrawRequest[_tokenId];
require(
stakeManager.epoch() >= usersRequest.requestEpoch,
"Not able to claim yet"
);
poLidoNFT.burn(_tokenId);
uint256 amountToClaim;
if (usersRequest.validatorAddress != address(0)) {
uint256 balanceBeforeClaim = IERC20Upgradeable(token).balanceOf(
address(this)
);
unstakeClaimTokens_new(
usersRequest.validatorAddress,
usersRequest.validatorNonce
);
amountToClaim =
IERC20Upgradeable(token).balanceOf(address(this)) -
balanceBeforeClaim;
} else {
amountToClaim = usersRequest.amount2WithdrawFromStMATIC;
reservedFunds -= amountToClaim;
totalBuffered -= amountToClaim;
}
IERC20Upgradeable(token).safeTransfer(msg.sender, amountToClaim);
emit ClaimTokensEvent(msg.sender, _tokenId, amountToClaim, 0);
}
/**
* @dev Distributes rewards claimed from validator shares based on fees defined in entityFee
*/
function distributeRewards() external override whenNotPaused {
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(true, false);
uint256 operatorInfosLength = operatorInfos.length;
for (uint256 i = 0; i < operatorInfosLength; i++) {
IValidatorShare validatorShare = IValidatorShare(
operatorInfos[i].validatorShare
);
uint256 stMaticReward = validatorShare.getLiquidRewards(
address(this)
);
uint256 rewardThreshold = validatorShare.minAmount();
if (stMaticReward >= rewardThreshold) {
validatorShare.withdrawRewards();
}
}
uint256 totalRewards = (
(IERC20Upgradeable(token).balanceOf(address(this)) - totalBuffered)
) / 10;
require(
totalRewards > rewardDistributionLowerBound,
"Amount to distribute lower than minimum"
);
uint256 balanceBeforeDistribution = IERC20Upgradeable(token).balanceOf(
address(this)
);
uint256 daoRewards = (totalRewards * entityFees.dao) / 100;
uint256 insuranceRewards = (totalRewards * entityFees.insurance) / 100;
uint256 operatorsRewards = (totalRewards * entityFees.operators) / 100;
uint256 operatorReward = operatorsRewards / operatorInfosLength;
IERC20Upgradeable(token).safeTransfer(dao, daoRewards);
IERC20Upgradeable(token).safeTransfer(insurance, insuranceRewards);
for (uint256 i = 0; i < operatorInfosLength; i++) {
IERC20Upgradeable(token).safeTransfer(
operatorInfos[i].rewardAddress,
operatorReward
);
}
uint256 currentBalance = IERC20Upgradeable(token).balanceOf(
address(this)
);
uint256 totalDistributed = balanceBeforeDistribution - currentBalance;
// Add the remainder to totalBuffered
totalBuffered = currentBalance;
emit DistributeRewardsEvent(totalDistributed);
}
/**
* @notice Only NodeOperatorRegistry can call this function
* @dev Withdraws funds from unstaked validator
* @param _validatorShare - Address of the validator share that will be withdrawn
*/
function withdrawTotalDelegated(address _validatorShare) external override {
require(
msg.sender == address(nodeOperatorRegistry),
"Not a node operator"
);
(uint256 stakedAmount, ) = getTotalStake(
IValidatorShare(_validatorShare)
);
if (stakedAmount == 0) {
return;
}
sellVoucher_new(_validatorShare, stakedAmount, type(uint256).max);
stMaticWithdrawRequest.push(
RequestWithdraw(
uint256(0),
IValidatorShare(_validatorShare).unbondNonces(address(this)),
stakeManager.epoch() + stakeManager.withdrawalDelay(),
_validatorShare
)
);
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalSupply(), getTotalPooledMatic())
);
emit WithdrawTotalDelegatedEvent(_validatorShare, stakedAmount);
}
/**
* @dev Claims tokens from validator share and sends them to the
* StMATIC contract
* @param _index - index the request.
*/
function claimTotalDelegated2StMatic(uint256 _index)
external
override
whenNotPaused
{
uint256 length = stMaticWithdrawRequest.length;
require(_index < length, "invalid index");
RequestWithdraw memory lidoRequests = stMaticWithdrawRequest[_index];
require(
stakeManager.epoch() >= lidoRequests.requestEpoch,
"Not able to claim yet"
);
uint256 balanceBeforeClaim = IERC20Upgradeable(token).balanceOf(
address(this)
);
unstakeClaimTokens_new(
lidoRequests.validatorAddress,
lidoRequests.validatorNonce
);
uint256 claimedAmount = IERC20Upgradeable(token).balanceOf(
address(this)
) - balanceBeforeClaim;
totalBuffered += claimedAmount;
if (_index != length - 1 && length != 1) {
stMaticWithdrawRequest[_index] = stMaticWithdrawRequest[length - 1];
}
stMaticWithdrawRequest.pop();
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalSupply(), getTotalPooledMatic())
);
emit ClaimTotalDelegatedEvent(address(this), claimedAmount);
}
/**
* @dev Flips the pause state
*/
function togglePause() external override onlyRole(DEFAULT_ADMIN_ROLE) {
paused() ? _unpause() : _pause();
}
////////////////////////////////////////////////////////////
///// ///
///// ***ValidatorShare API*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev API for delegated buying vouchers from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _amount - Amount of MATIC to use for buying vouchers
* @param _minSharesToMint - Minimum of shares that is bought with _amount of MATIC
* @return Actual amount of MATIC used to buy voucher, might differ from _amount because of _minSharesToMint
*/
function buyVoucher(
address _validatorShare,
uint256 _amount,
uint256 _minSharesToMint
) private returns (uint256) {
uint256 amountSpent = IValidatorShare(_validatorShare).buyVoucher(
_amount,
_minSharesToMint
);
return amountSpent;
}
/**
* @dev API for delegated restaking rewards to validatorShare
* @param _validatorShare - Address of validatorShare contract
*/
function restake(address _validatorShare) private {
IValidatorShare(_validatorShare).restake();
}
/**
* @dev API for delegated unstaking and claiming tokens from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _unbondNonce - Unbond nonce
*/
function unstakeClaimTokens_new(
address _validatorShare,
uint256 _unbondNonce
) private {
IValidatorShare(_validatorShare).unstakeClaimTokens_new(_unbondNonce);
}
/**
* @dev API for delegated selling vouchers from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _claimAmount - Amount of MATIC to claim
* @param _maximumSharesToBurn - Maximum amount of shares to burn
*/
function sellVoucher_new(
address _validatorShare,
uint256 _claimAmount,
uint256 _maximumSharesToBurn
) private {
IValidatorShare(_validatorShare).sellVoucher_new(
_claimAmount,
_maximumSharesToBurn
);
}
/**
* @dev API for getting total stake of this contract from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @return Total stake of this contract and MATIC -> share exchange rate
*/
function getTotalStake(IValidatorShare _validatorShare)
public
view
override
returns (uint256, uint256)
{
return _validatorShare.getTotalStake(address(this));
}
/**
* @dev API for liquid rewards of this contract from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @return Liquid rewards of this contract
*/
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
override
returns (uint256)
{
return _validatorShare.getLiquidRewards(address(this));
}
////////////////////////////////////////////////////////////
///// ///
///// ***Helpers & Utilities*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev Returns the stMaticWithdrawRequest list
*/
function getTotalWithdrawRequest()
public
view
returns (RequestWithdraw[] memory)
{
return stMaticWithdrawRequest;
}
/**
* @dev Helper function for that returns total pooled MATIC
* @return Total pooled MATIC
*/
function getTotalStakeAcrossAllValidators()
public
view
override
returns (uint256)
{
uint256 totalStake;
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
uint256 operatorInfosLength = operatorInfos.length;
for (uint256 i = 0; i < operatorInfosLength; i++) {
(uint256 currValidatorShare, ) = getTotalStake(
IValidatorShare(operatorInfos[i].validatorShare)
);
totalStake += currValidatorShare;
}
return totalStake;
}
/**
* @dev Function that calculates total pooled Matic
* @return Total pooled Matic
*/
function getTotalPooledMatic() public view override returns (uint256) {
uint256 totalStaked = getTotalStakeAcrossAllValidators();
return
totalStaked +
totalBuffered +
calculatePendingBufferedTokens() -
reservedFunds;
}
/**
* @dev Function that converts arbitrary stMATIC to Matic
* @param _balance - Balance in stMATIC
* @return Balance in Matic, totalShares and totalPooledMATIC
*/
function convertStMaticToMatic(uint256 _balance)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 totalShares = totalSupply();
totalShares = totalShares == 0 ? 1 : totalShares;
uint256 totalPooledMATIC = getTotalPooledMatic();
totalPooledMATIC = totalPooledMATIC == 0 ? 1 : totalPooledMATIC;
uint256 balanceInMATIC = (_balance * totalPooledMATIC) / totalShares;
return (balanceInMATIC, totalShares, totalPooledMATIC);
}
/**
* @dev Function that converts arbitrary Matic to stMATIC
* @param _balance - Balance in Matic
* @return Balance in stMATIC, totalShares and totalPooledMATIC
*/
function convertMaticToStMatic(uint256 _balance)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 totalShares = totalSupply();
totalShares = totalShares == 0 ? 1 : totalShares;
uint256 totalPooledMatic = getTotalPooledMatic();
totalPooledMatic = totalPooledMatic == 0 ? 1 : totalPooledMatic;
uint256 balanceInStMatic = (_balance * totalShares) / totalPooledMatic;
return (balanceInStMatic, totalShares, totalPooledMatic);
}
/**
* @dev Function that calculates minimal allowed validator balance (lower bound)
* @return Minimal validator balance in MATIC
*/
function getMinValidatorBalance() external view override returns (uint256) {
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
return _getMinValidatorBalance(operatorInfos);
}
function _getMinValidatorBalance(
Operator.OperatorInfo[] memory operatorInfos
) private view returns (uint256) {
uint256 operatorInfosLength = operatorInfos.length;
uint256 minValidatorBalance = type(uint256).max;
for (uint256 i = 0; i < operatorInfosLength; i++) {
(uint256 validatorShare, ) = getTotalStake(
IValidatorShare(operatorInfos[i].validatorShare)
);
// 10% of current validatorShare
uint256 minValidatorBalanceCurrent = validatorShare / 10;
if (
minValidatorBalanceCurrent != 0 &&
minValidatorBalanceCurrent < minValidatorBalance
) {
minValidatorBalance = minValidatorBalanceCurrent;
}
}
return minValidatorBalance;
}
////////////////////////////////////////////////////////////
///// ///
///// ***Setters*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev Function that sets entity fees
* @notice Callable only by dao
* @param _daoFee - DAO fee in %
* @param _operatorsFee - Operator fees in %
* @param _insuranceFee - Insurance fee in %
*/
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external override onlyRole(DAO) {
require(
_daoFee + _operatorsFee + _insuranceFee == 100,
"sum(fee)!=100"
);
entityFees.dao = _daoFee;
entityFees.operators = _operatorsFee;
entityFees.insurance = _insuranceFee;
}
/**
* @dev Function that sets new dao address
* @notice Callable only by dao
* @param _address - New dao address
*/
function setDaoAddress(address _address) external override onlyRole(DAO) {
revokeRole(DAO, dao);
dao = _address;
_setupRole(DAO, dao);
}
/**
* @dev Function that sets new insurance address
* @notice Callable only by dao
* @param _address - New insurance address
*/
function setInsuranceAddress(address _address)
external
override
onlyRole(DAO)
{
insurance = _address;
}
/**
* @dev Function that sets new node operator address
* @notice Only callable by dao
* @param _address - New node operator address
*/
function setNodeOperatorRegistryAddress(address _address)
external
override
onlyRole(DAO)
{
nodeOperatorRegistry = INodeOperatorRegistry(_address);
}
/**
* @dev Function that sets new lower bound for delegation
* @notice Only callable by dao
* @param _delegationLowerBound - New lower bound for delegation
*/
function setDelegationLowerBound(uint256 _delegationLowerBound)
external
override
onlyRole(DAO)
{
delegationLowerBound = _delegationLowerBound;
}
/**
* @dev Function that sets new lower bound for rewards distribution
* @notice Only callable by dao
* @param _rewardDistributionLowerBound - New lower bound for rewards distribution
*/
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external override onlyRole(DAO) {
rewardDistributionLowerBound = _rewardDistributionLowerBound;
}
/**
* @dev Function that sets the poLidoNFT address
* @param _poLidoNFT new poLidoNFT address
*/
function setPoLidoNFT(address _poLidoNFT) external override onlyRole(DAO) {
poLidoNFT = IPoLidoNFT(_poLidoNFT);
}
/**
* @dev Function that sets the fxStateRootTunnel address
* @param _fxStateRootTunnel address of fxStateRootTunnel
*/
function setFxStateRootTunnel(address _fxStateRootTunnel)
external
override
onlyRole(DAO)
{
fxStateRootTunnel = IFxStateRootTunnel(_fxStateRootTunnel);
}
/**
* @dev Function that sets the submitThreshold
* @param _submitThreshold new value for submit threshold
*/
function setSubmitThreshold(uint256 _submitThreshold)
external
override
onlyRole(DAO)
{
submitThreshold = _submitThreshold;
}
/**
* @dev Function that sets the submitHandler value to its NOT value
*/
function flipSubmitHandler() external override onlyRole(DAO) {
submitHandler = !submitHandler;
}
/**
* @dev Function that sets the new version
* @param _version - New version that will be set
*/
function setVersion(string calldata _version)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
version = _version;
}
/**
* @dev Function that retrieves the amount of matic that will be claimed from the NFT token
* @param _tokenId - Id of the PolidoNFT
*/
function getMaticFromTokenId(uint256 _tokenId)
public
view
override
returns (uint256)
{
return _getMaticFromRequestWithdraw(token2WithdrawRequest[_tokenId]);
}
function _getMaticFromRequestWithdraw(RequestWithdraw memory requestData)
public
view
returns (uint256)
{
if (requestData.validatorAddress == address(0)) {
return requestData.amount2WithdrawFromStMATIC;
}
IValidatorShare validatorShare = IValidatorShare(
requestData.validatorAddress
);
uint256 validatorId = validatorShare.validatorId();
// see here for more details about how to exchangeRatePrecision is calculated:
// https://github.com/maticnetwork/contracts/blob/v0.3.0-backport/contracts/staking/validatorShare/ValidatorShare.sol#L313
uint256 exchangeRatePrecision = validatorId < 8 ? 100 : 10**29;
uint256 withdrawExchangeRate = validatorShare.withdrawExchangeRate();
IValidatorShare.DelegatorUnbond memory unbond = validatorShare
.unbonds_new(address(this), requestData.validatorNonce);
return (withdrawExchangeRate * unbond.shares) / exchangeRatePrecision;
}
/**
* @dev Function that calculates the total pending buffered tokens in LidoNFT contract.
*/
function calculatePendingBufferedTokens()
public
view
returns (uint256 pendingBufferedTokens)
{
RequestWithdraw[] memory requestData = stMaticWithdrawRequest;
uint256 length = requestData.length;
for (uint256 i = 0; i < length; i++) {
pendingBufferedTokens += _getMaticFromRequestWithdraw(requestData[i]);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_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.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IValidatorShare {
struct DelegatorUnbond {
uint256 shares;
uint256 withdrawEpoch;
}
function unbondNonces(address _address) external view returns (uint256);
function activeAmount() external view returns (uint256);
function validatorId() external view returns (uint256);
function withdrawExchangeRate() external view returns (uint256);
function withdrawRewards() external;
function unstakeClaimTokens() external;
function minAmount() external view returns (uint256);
function getLiquidRewards(address user) external view returns (uint256);
function delegation() external view returns (bool);
function updateDelegation(bool _delegation) external;
function buyVoucher(uint256 _amount, uint256 _minSharesToMint)
external
returns (uint256);
function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn)
external;
function unstakeClaimTokens_new(uint256 unbondNonce) external;
function unbonds_new(address _address, uint256 _unbondNonce)
external
view
returns (DelegatorUnbond memory);
function getTotalStake(address user)
external
view
returns (uint256, uint256);
function owner() external view returns (address);
function restake() external returns (uint256, uint256);
function unlock() external;
function lock() external;
function drain(
address token,
address payable destination,
uint256 amount
) external;
function slash(uint256 _amount) external;
function migrateOut(address user, uint256 amount) external;
function migrateIn(address user, uint256 amount) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../lib/Operator.sol";
/// @title INodeOperatorRegistry
/// @author 2021 ShardLabs
/// @notice Node operator registry interface
interface INodeOperatorRegistry {
/// @notice Allows to add a new node operator to the system.
/// @param _name the node operator name.
/// @param _rewardAddress public address used for ACL and receive rewards.
/// @param _signerPubkey public key used on heimdall len 64 bytes.
function addOperator(
string memory _name,
address _rewardAddress,
bytes memory _signerPubkey
) external;
/// @notice Allows to stop a node operator.
/// @param _operatorId node operator id.
function stopOperator(uint256 _operatorId) external;
/// @notice Allows to remove a node operator from the system.
/// @param _operatorId node operator id.
function removeOperator(uint256 _operatorId) external;
/// @notice Allows a staked validator to join the system.
function joinOperator() external;
/// @notice Allows to stake an operator on the Polygon stakeManager.
/// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee)
/// has to be approved first.
/// @param _amount amount to stake.
/// @param _heimdallFee heimdallFee to stake.
function stake(uint256 _amount, uint256 _heimdallFee) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param _amount amount to stake.
/// @param _restakeRewards restake rewards.
function restake(uint256 _amount, bool _restakeRewards) external;
/// @notice Allows the operator's owner to migrate the NFT. This can be done only
/// if the DAO stopped the operator.
function migrate() external;
/// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay
/// the operator owner can call claimStake func to withdraw the staked tokens.
function unstake() external;
/// @notice Allows to topup heimdall fees on polygon stakeManager.
/// @param _heimdallFee amount to topup.
function topUpForFee(uint256 _heimdallFee) external;
/// @notice Allows to claim staked tokens on the stake Manager after the end of the
/// withdraw delay
function unstakeClaim() external;
/// @notice Allows an owner to withdraw rewards from the stakeManager.
function withdrawRewards() external;
/// @notice Allows to update the signer pubkey
/// @param _signerPubkey update signer public key
function updateSigner(bytes memory _signerPubkey) external;
/// @notice Allows to claim the heimdall fees staked by the owner of the operator
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED
function unjail() external;
/// @notice Allows an operator's owner to set the operator name.
function setOperatorName(string memory _name) external;
/// @notice Allows an operator's owner to set the operator rewardAddress.
function setOperatorRewardAddress(address _rewardAddress) external;
/// @notice Allows the DAO to set _defaultMaxDelegateLimit.
function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external;
/// @notice Allows the DAO to set _maxDelegateLimit for an operator.
function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit)
external;
/// @notice Allows the DAO to set _commissionRate.
function setCommissionRate(uint256 _commissionRate) external;
/// @notice Allows the DAO to set _commissionRate for an operator.
/// @param _operatorId id of the operator
/// @param _newCommissionRate new commission rate
function updateOperatorCommissionRate(
uint256 _operatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees.
function setStakeAmountAndFees(
uint256 _minAmountStake,
uint256 _minHeimdallFees
) external;
/// @notice Allows to pause/unpause the node operator contract.
function togglePause() external;
/// @notice Allows the DAO to enable/disable restake.
function setRestake(bool _restake) external;
/// @notice Allows the DAO to set stMATIC contract.
function setStMATIC(address _stMATIC) external;
/// @notice Allows the DAO to set validator factory contract.
function setValidatorFactory(address _validatorFactory) external;
/// @notice Allows the DAO to set stake manager contract.
function setStakeManager(address _stakeManager) external;
/// @notice Allows to set contract version.
function setVersion(string memory _version) external;
/// @notice Get the stMATIC contract addresses
function getContracts()
external
view
returns (
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
);
/// @notice Allows to get stats.
function getState()
external
view
returns (
uint256 _totalNodeOperator,
uint256 _totalInactiveNodeOperator,
uint256 _totalActiveNodeOperator,
uint256 _totalStoppedNodeOperator,
uint256 _totalUnstakedNodeOperator,
uint256 _totalClaimedNodeOperator,
uint256 _totalExitNodeOperator,
uint256 _totalSlashedNodeOperator,
uint256 _totalEjectedNodeOperator
);
/// @notice Allows to get a list of operatorInfo.
function getOperatorInfos(bool _delegation, bool _allActive)
external
view
returns (Operator.OperatorInfo[] memory);
/// @notice Allows to get all the operator ids.
function getOperatorIds() external view returns (uint256[] memory);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
/// @title polygon stake manager interface.
/// @author 2021 ShardLabs
/// @notice User to interact with the polygon stake manager.
interface IStakeManager {
/// @notice Stake a validator on polygon stake manager.
/// @param user user that own the validator in our case the validator contract.
/// @param amount amount to stake.
/// @param heimdallFee heimdall fees.
/// @param acceptDelegation accept delegation.
/// @param signerPubkey signer publickey used in heimdall node.
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param validatorId validator id.
/// @param amount amount to stake.
/// @param stakeRewards restake rewards.
function restake(
uint256 validatorId,
uint256 amount,
bool stakeRewards
) external;
/// @notice Request unstake a validator.
/// @param validatorId validator id.
function unstake(uint256 validatorId) external;
/// @notice Increase the heimdall fees.
/// @param user user that own the validator in our case the validator contract.
/// @param heimdallFee heimdall fees.
function topUpForFee(address user, uint256 heimdallFee) external;
/// @notice Get the validator id using the user address.
/// @param user user that own the validator in our case the validator contract.
/// @return return the validator id
function getValidatorId(address user) external view returns (uint256);
/// @notice get the validator contract used for delegation.
/// @param validatorId validator id.
/// @return return the address of the validator contract.
function getValidatorContract(uint256 validatorId)
external
view
returns (address);
/// @notice Withdraw accumulated rewards
/// @param validatorId validator id.
function withdrawRewards(uint256 validatorId) external;
/// @notice Get validator total staked.
/// @param validatorId validator id.
function validatorStake(uint256 validatorId)
external
view
returns (uint256);
/// @notice Allows to unstake the staked tokens on the stakeManager.
/// @param validatorId validator id.
function unstakeClaim(uint256 validatorId) external;
/// @notice Allows to update the signer pubkey
/// @param _validatorId validator id
/// @param _signerPubkey update signer public key
function updateSigner(uint256 _validatorId, bytes memory _signerPubkey)
external;
/// @notice Allows to claim the heimdall fees.
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to update the commision rate of a validator
/// @param _validatorId operator id
/// @param _newCommissionRate commission rate
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows to unjail a validator.
/// @param _validatorId id of the validator that is to be unjailed
function unjail(uint256 _validatorId) external;
/// @notice Returns a withdrawal delay.
function withdrawalDelay() external view returns (uint256);
/// @notice Transfers amount from delegator
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function epoch() external view returns (uint256);
enum Status {
Inactive,
Active,
Locked,
Unstaked
}
struct Validator {
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
uint256 commissionRate;
uint256 lastCommissionUpdate;
uint256 delegatorsReward;
uint256 delegatedAmount;
uint256 initialRewardPerStake;
}
function validators(uint256 _index)
external
view
returns (Validator memory);
/// @notice Returns the address of the nft contract
function NFTContract() external view returns (address);
/// @notice Returns the validator accumulated rewards on stake manager.
function validatorReward(uint256 validatorId)
external
view
returns (uint256);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/// @title PoLidoNFT interface.
/// @author 2021 ShardLabs
interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
function getOwnedTokens(address _address) external view returns (uint256[] memory);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IFxStateRootTunnel {
function latestData() external view returns (bytes memory);
function setFxChildTunnel(address _fxChildTunnel) external;
function sendMessageToChild(bytes memory message) external;
function setStMATIC(address _stMATIC) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./IValidatorShare.sol";
import "./INodeOperatorRegistry.sol";
import "./INodeOperatorRegistry.sol";
import "./IStakeManager.sol";
import "./IPoLidoNFT.sol";
import "./IFxStateRootTunnel.sol";
/// @title StMATIC interface.
/// @author 2021 ShardLabs
interface IStMATIC is IERC20Upgradeable {
struct RequestWithdraw {
uint256 amount2WithdrawFromStMATIC;
uint256 validatorNonce;
uint256 requestEpoch;
address validatorAddress;
}
struct FeeDistribution {
uint8 dao;
uint8 operators;
uint8 insurance;
}
function withdrawTotalDelegated(address _validatorShare) external;
function nodeOperatorRegistry() external returns (INodeOperatorRegistry);
function entityFees()
external
returns (
uint8,
uint8,
uint8
);
function getMaticFromTokenId(uint256 _tokenId)
external
view
returns (uint256);
function stakeManager() external view returns (IStakeManager);
function poLidoNFT() external view returns (IPoLidoNFT);
function fxStateRootTunnel() external view returns (IFxStateRootTunnel);
function version() external view returns (string memory);
function dao() external view returns (address);
function insurance() external view returns (address);
function token() external view returns (address);
function lastWithdrawnValidatorId() external view returns (uint256);
function totalBuffered() external view returns (uint256);
function delegationLowerBound() external view returns (uint256);
function rewardDistributionLowerBound() external view returns (uint256);
function reservedFunds() external view returns (uint256);
function submitThreshold() external view returns (uint256);
function submitHandler() external view returns (bool);
function getMinValidatorBalance() external view returns (uint256);
function token2WithdrawRequest(uint256 _requestId)
external
view
returns (
uint256,
uint256,
uint256,
address
);
function DAO() external view returns (bytes32);
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external;
function submit(uint256 _amount) external returns (uint256);
function requestWithdraw(uint256 _amount) external;
function delegate() external;
function claimTokens(uint256 _tokenId) external;
function distributeRewards() external;
function claimTotalDelegated2StMatic(uint256 _index) external;
function togglePause() external;
function getTotalStake(IValidatorShare _validatorShare)
external
view
returns (uint256, uint256);
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
returns (uint256);
function getTotalStakeAcrossAllValidators() external view returns (uint256);
function getTotalPooledMatic() external view returns (uint256);
function convertStMaticToMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function convertMaticToStMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external;
function setDaoAddress(address _address) external;
function setInsuranceAddress(address _address) external;
function setNodeOperatorRegistryAddress(address _address) external;
function setDelegationLowerBound(uint256 _delegationLowerBound) external;
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external;
function setPoLidoNFT(address _poLidoNFT) external;
function setFxStateRootTunnel(address _fxStateRootTunnel) external;
function setSubmitThreshold(uint256 _submitThreshold) external;
function flipSubmitHandler() external;
function setVersion(string calldata _version) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
library Operator {
struct OperatorInfo {
uint256 operatorId;
address validatorShare;
uint256 maxDelegateLimit;
address rewardAddress;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
|
Returns the address of the nft contract Returns the validator accumulated rewards on stake manager. SPDX-FileCopyrightText: 2021 ShardLabs SPDX-License-Identifier: GPL-3.0 PoLidoNFT interface. 2021 ShardLabs
|
interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
function getOwnedTokens(address _address) external view returns (uint256[] memory);
}
| 11,789,401 |
./partial_match/4/0x1116b09D790D897704346cd72a05aAA384802192/sources/home/robert/Github/smartys-develop/truffle-blokko/contracts/BlokkoOrder.sol
|
Scenario green: cancelled within delivery time Scenario red: cancelled outside delivery time
|
function cancelOrder(bytes memory userData) public {
uint256 _selectedOrderID = bytesToUint(userData);
uint256 _deliveryEnd = uint64(block.timestamp);
uint256 _totalAmount = orders[_selectedOrderID].transportAmount.add(orders[_selectedOrderID].orderAmount);
require(msg.sender == orders[_selectedOrderID].client, "Only client can call this function.");
require(orders[_selectedOrderID].status.escrowPaid == true, "No escrow has been deposited.");
require(orders[_selectedOrderID].status.orderEnded == false, "Transport already ended.");
if (_deliveryEnd <= orders[_selectedOrderID].deliveryTime ) {
blokkoToken.send(orders[_selectedOrderID].client, orders[_selectedOrderID].orderAmount, userData);
blokkoToken.send(orders[_selectedOrderID].supplier, orders[_selectedOrderID].transportAmount, userData);
orders[_selectedOrderID].status.status = "5-cancelledOnTime";
blokkoToken.send(orders[_selectedOrderID].client, _totalAmount, userData);
orders[_selectedOrderID].status.status = "6-cancelledLate";
}
orders[_selectedOrderID].status.orderEnded = true;
emit orderCancelled(orders[_selectedOrderID].status.status, _selectedOrderID, orders[_selectedOrderID].status.orderEnded);
}
event depositedStatus(bool escrowPaid);
| 8,629,199 |
./full_match/1/0x6C5c2c8776Ecc5943760C68a200eC7e3650eFC2F/sources/contracts/paymaster/TokenPaymaster.sol
|
Sets the token whitelist mode for the specified token. token The address of the token to set the whitelist mode for mode Boolean value to set the token whitelist mode to whitelist (true) or blacklist (false)/
|
function setTokenWhitelistMode(address token, bool mode) public payable {
_setTokenWhitelistMode(token, msg.sender, mode);
emit SetTokenWhitelistMode(token, msg.sender, mode);
}
| 16,537,833 |
./partial_match/1/0x7D464cc85C960De8D3A909Cdc1a0A163412C0348/sources/CatnipV2.sol
|
Set the mining difficulty for catnipV2 mining. _amount New difficulty amount./
|
function setMiningDifficulty(uint256 _amount) public _onlyOwner delegatedOnly {
miningDifficulty = _amount;
}
| 2,838,587 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./helpers.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract InstaVaultResolver is Helpers {
struct VaultInfo {
address token;
uint8 decimals;
uint256 tokenMinLimit;
address atoken;
address vaultDsa;
VaultInterface.Ratios ratios;
uint256 exchangePrice;
uint256 lastRevenueExchangePrice;
uint256 revenueFee;
uint256 revenue;
uint256 revenueEth;
uint256 withdrawalFee;
uint256 idealExcessAmt;
uint256 swapFee;
uint256 saveSlippage;
uint256 vTokenTotalSupply;
uint256 tokenCollateralAmt_;
uint256 tokenVaultBal_;
uint256 tokenDSABal_;
uint256 netTokenBal_;
uint256 stethCollateralAmt_;
uint256 stethVaultBal_;
uint256 stethDSABal_;
uint256 wethDebtAmt_;
uint256 wethVaultBal_;
uint256 wethDSABal_;
}
function getVaultInfo(address vaultAddr_)
public
view
returns (VaultInfo memory vaultInfo_)
{
VaultInterface vault = VaultInterface(vaultAddr_);
vaultInfo_.token = vault.token();
vaultInfo_.decimals = vault.decimals();
vaultInfo_.tokenMinLimit = vault.tokenMinLimit();
vaultInfo_.atoken = vault.atoken();
vaultInfo_.vaultDsa = vault.vaultDsa();
vaultInfo_.ratios = vault.ratios();
(vaultInfo_.exchangePrice, ) = vault.getCurrentExchangePrice();
vaultInfo_.lastRevenueExchangePrice = vault.lastRevenueExchangePrice();
vaultInfo_.revenueFee = vault.revenueFee();
vaultInfo_.revenue = vault.revenue();
vaultInfo_.revenueEth = vault.revenueEth();
vaultInfo_.withdrawalFee = vault.withdrawalFee();
vaultInfo_.idealExcessAmt = vault.idealExcessAmt();
vaultInfo_.swapFee = vault.swapFee();
vaultInfo_.saveSlippage = vault.saveSlippage();
vaultInfo_.vTokenTotalSupply = vault.totalSupply();
(vaultInfo_.tokenCollateralAmt_, vaultInfo_.stethCollateralAmt_, vaultInfo_.wethDebtAmt_, vaultInfo_.tokenVaultBal_, vaultInfo_.tokenDSABal_, vaultInfo_.netTokenBal_) = vault.getVaultBalances();
vaultInfo_.stethVaultBal_ = IERC20(stEthAddr).balanceOf(vaultAddr_);
vaultInfo_.stethDSABal_ = IERC20(stEthAddr).balanceOf(vaultInfo_.vaultDsa);
vaultInfo_.wethVaultBal_ = IERC20(wethAddr).balanceOf(vaultAddr_);
vaultInfo_.wethDSABal_ = IERC20(wethAddr).balanceOf(vaultInfo_.vaultDsa);
}
struct UserInfo {
address vaultAddr;
VaultInfo vaultInfo;
uint256 vtokenBal;
uint256 amount;
}
function getUserInfo(address[] memory vaults_, address user_)
public
view
returns (UserInfo[] memory userInfos_)
{
userInfos_ = new UserInfo[](vaults_.length);
for (uint i = 0; i < vaults_.length; i++) {
VaultInterface vault = VaultInterface(vaults_[i]);
userInfos_[i].vaultInfo = getVaultInfo(vaults_[i]);
userInfos_[i].vtokenBal = vault.balanceOf(user_);
userInfos_[i].amount = (userInfos_[i].vtokenBal * userInfos_[i].vaultInfo.exchangePrice) / 1e18;
}
}
function collectProfitData(address vaultAddr_, bool isWeth_) public view returns (uint256 withdrawAmt_, uint256 amt_) {
VaultInterface vault = VaultInterface(vaultAddr_);
uint256 profits_ = (vault.getNewProfits() * 99) / 100; // keeping 1% margin
uint256 vaultBal_;
if (isWeth_) vaultBal_ = IERC20(wethAddr).balanceOf(vaultAddr_);
else vaultBal_ = IERC20(stEthAddr).balanceOf(vaultAddr_);
(,uint stethCollateralAmt_,,,,) = vault.getVaultBalances();
if (profits_ <= vaultBal_) {
withdrawAmt_ = 0;
} else {
uint maxAmt_ = (stethCollateralAmt_ * vault.idealExcessAmt()) / 10000;
maxAmt_ = (maxAmt_ * 99) / 100; // keeping 1% margin
withdrawAmt_ = maxAmt_ + profits_ - vaultBal_;
}
amt_ = profits_;
}
struct RebalanceOneVariables {
address tokenAddr;
uint256 tokenDecimals;
uint256 tokenMinLimit;
uint256 tokenVaultBal;
uint256 netTokenBal;
VaultInterface.Ratios ratios;
uint256 stethCollateral;
uint256 wethDebt;
uint256 ethCoveringDebt;
uint256 excessDebt;
uint256 tokenPriceInEth;
uint netTokenSupplyInEth;
uint256 currentRatioMin;
uint256[] deleverageAmts;
}
function rebalanceOneData(address vaultAddr_, address[] memory vaultsToCheck_)
public
view
returns (
address flashTkn_, // currently its always weth addr
uint256 flashAmt_,
uint256 route_,
address[] memory vaults_,
uint256[] memory amts_,
uint256 leverageAmt_,
uint256 swapAmt_,
uint256 tokenSupplyAmt_,
uint256 tokenWithdrawAmt_ // currently always returned zero
)
{
RebalanceOneVariables memory v_;
VaultInterface vault_ = VaultInterface(vaultAddr_);
v_.tokenAddr = vault_.token();
v_.tokenDecimals = vault_.decimals();
v_.tokenMinLimit = vault_.tokenMinLimit();
(, v_.stethCollateral, v_.wethDebt, v_.tokenVaultBal,, v_.netTokenBal) = vault_.getVaultBalances();
if (v_.tokenVaultBal > v_.tokenMinLimit) tokenSupplyAmt_ = v_.tokenVaultBal;
v_.ratios = vault_.ratios();
v_.ethCoveringDebt = (v_.stethCollateral * v_.ratios.stEthLimit) / 10000;
v_.excessDebt = v_.ethCoveringDebt < v_.wethDebt ? v_.wethDebt - v_.ethCoveringDebt : 0;
v_.tokenPriceInEth = IAavePriceOracle(aaveAddressProvider.getPriceOracle()).getAssetPrice(v_.tokenAddr);
v_.netTokenSupplyInEth = (v_.netTokenBal * v_.tokenPriceInEth) / (10 ** v_.tokenDecimals);
v_.currentRatioMin = v_.netTokenSupplyInEth == 0 ? 0 : (v_.excessDebt * 10000) / v_.netTokenSupplyInEth;
if (v_.currentRatioMin < v_.ratios.minLimitGap) {
// keeping 0.1% margin for final ratio
leverageAmt_ = (((v_.ratios.minLimit - 10) - v_.currentRatioMin) * v_.netTokenSupplyInEth) / (10000 - v_.ratios.stEthLimit);
flashTkn_ = wethAddr;
// TODO: dont take flashloan if not needed
flashAmt_ = (v_.netTokenSupplyInEth / 10) + (leverageAmt_ * 10 / 8); // 10% of current collateral(in eth) + leverageAmt_ / 0.8
route_ = 5;
v_.deleverageAmts = getMaxDeleverageAmts(vaultsToCheck_);
(vaults_, amts_, swapAmt_) = getVaultsToUse(vaultsToCheck_, v_.deleverageAmts, leverageAmt_);
}
}
struct RebalanceTwoVariables {
address tokenAddr;
uint256 tokenDecimals;
uint256 tokenMinLimit;
uint256 stethCollateral;
uint256 wethDebt;
uint256 tokenVaultBal;
uint256 netTokenBal;
VaultInterface.Ratios ratios;
uint256 ethCoveringDebt;
uint256 excessDebt;
uint256 tokenPriceInEth;
uint netTokenCollateralInEth;
uint256 currentRatioMax;
}
function rebalanceTwoData(address vaultAddr_)
public
view
returns (
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 tokenSupplyAmt_
)
{
VaultInterface vault_ = VaultInterface(vaultAddr_);
RebalanceTwoVariables memory v_;
v_.tokenAddr = vault_.token();
v_.tokenDecimals = vault_.decimals();
v_.tokenMinLimit = vault_.tokenMinLimit();
(, v_.stethCollateral, v_.wethDebt, v_.tokenVaultBal,, v_.netTokenBal) = vault_.getVaultBalances();
if (v_.tokenVaultBal > v_.tokenMinLimit) tokenSupplyAmt_ = v_.tokenVaultBal;
VaultInterface.Ratios memory ratios_ = vault_.ratios();
v_.ethCoveringDebt = (v_.stethCollateral * ratios_.stEthLimit) / 10000;
v_.excessDebt = v_.ethCoveringDebt < v_.wethDebt ? v_.wethDebt - v_.ethCoveringDebt : 0;
v_.tokenPriceInEth = IAavePriceOracle(aaveAddressProvider.getPriceOracle()).getAssetPrice(v_.tokenAddr);
v_.netTokenCollateralInEth = (v_.netTokenBal * v_.tokenPriceInEth) / (10 ** v_.tokenDecimals);
v_.currentRatioMax = v_.netTokenCollateralInEth == 0 ? 0 : (v_.excessDebt * 10000) / v_.netTokenCollateralInEth;
if (v_.currentRatioMax > ratios_.maxLimit) {
saveAmt_ = ((v_.currentRatioMax - (ratios_.maxLimitGap + 10)) * v_.netTokenCollateralInEth) / (10000 - ratios_.stEthLimit);
flashTkn_ = wethAddr;
// TODO: dont take flashloan if not needed
flashAmt_ = (v_.netTokenCollateralInEth / 10) + (saveAmt_ * 10 / 8); // 10% of current collateral(in eth) + (leverageAmt_ / 0.8)
route_ = 5;
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./interfaces.sol";
contract Helpers {
IAaveAddressProvider internal constant aaveAddressProvider =
IAaveAddressProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
address internal constant wethAddr =
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant stEthAddr =
0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
function getMaxDeleverageAmt(address vaultAddr_) internal view returns (uint256 amount_) {
VaultInterface vault_ = VaultInterface(vaultAddr_);
address tokenAddr_ = vault_.token();
uint256 tokenDecimals_ = vault_.decimals();
(,uint stethCollateral_, uint wethDebt_,,, uint256 netTokenBal_) = vault_.getVaultBalances();
VaultInterface.Ratios memory ratios_ = vault_.ratios();
uint256 ethCoveringDebt_ = (stethCollateral_ * ratios_.stEthLimit) / 10000;
uint256 excessDebt_ = ethCoveringDebt_ < wethDebt_ ? wethDebt_ - ethCoveringDebt_ : 0;
uint256 tokenPriceInEth_ = IAavePriceOracle(aaveAddressProvider.getPriceOracle()).getAssetPrice(tokenAddr_);
uint netTokenSupplyInEth_ = (netTokenBal_ * tokenPriceInEth_) / (10 ** tokenDecimals_);
uint256 currentRatioMin_ = netTokenSupplyInEth_ == 0 ? 0 :(excessDebt_ * 10000) / netTokenSupplyInEth_;
if (currentRatioMin_ > ratios_.minLimit) {
// keeping 0.1% margin for final ratio
amount_ = ((currentRatioMin_ - (ratios_.minLimit + 10)) * netTokenSupplyInEth_) / (10000 + ratios_.stEthLimit);
}
}
function getMaxDeleverageAmts(address[] memory vaults_) internal view returns (uint256[] memory amounts_) {
amounts_ = new uint[](vaults_.length);
for (uint i = 0; i < vaults_.length; i++) {
amounts_[i] = getMaxDeleverageAmt(vaults_[i]);
}
}
function bubbleSort(address[] memory vaults_, uint256[] memory amounts_)
internal
pure
returns (address[] memory, uint256[] memory)
{
for (uint256 i = 0; i < amounts_.length - 1; i++) {
for (uint256 j = 0; j < amounts_.length - i - 1; j++) {
if (amounts_[j] < amounts_[j + 1]) {
(
vaults_[j],
vaults_[j + 1],
amounts_[j],
amounts_[j + 1]
) = (
vaults_[j + 1],
vaults_[j],
amounts_[j + 1],
amounts_[j]
);
}
}
}
return (vaults_, amounts_);
}
function getTrimmedArrays(
address[] memory vaults_,
uint256[] memory amounts_,
uint256 length_
) internal pure returns (address[] memory finalVaults_, uint256[] memory finalAmts_) {
finalVaults_ = new address[](length_);
finalAmts_ = new uint256[](length_);
for (uint256 i = 0; i < length_; i++) {
finalVaults_[i] = vaults_[i];
finalAmts_[i] = amounts_[i];
}
}
function getVaultsToUse(
address[] memory vaultsToCheck_,
uint256[] memory deleverageAmts_,
uint256 leverageAmt_
) internal pure returns (address[] memory vaults_, uint256[] memory amounts_, uint256 swapAmt_) {
(vaults_, amounts_) = bubbleSort(vaultsToCheck_, deleverageAmts_);
swapAmt_ = leverageAmt_;
uint i;
while (swapAmt_ > 0 && i < vaults_.length && amounts_[i] > 0) {
if (amounts_[i] > swapAmt_) amounts_[i] = swapAmt_;
swapAmt_ -= amounts_[i];
i++;
}
if (i != vaults_.length) (vaults_, amounts_) = getTrimmedArrays(vaults_, amounts_, i);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface IAaveAddressProvider {
function getPriceOracle() external view returns (address);
}
interface IAavePriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
}
interface VaultInterface {
function token() external view returns (address);
function decimals() external view returns (uint8);
function tokenMinLimit() external view returns (uint256);
function atoken() external view returns (address);
function vaultDsa() external view returns (address);
struct Ratios {
uint16 maxLimit; // Above this withdrawals are not allowed
uint16 maxLimitGap;
uint16 minLimit; // After leverage the ratio should be below minLimit & above minLimitGap
uint16 minLimitGap;
uint16 stEthLimit; // if 7500. Meaning stETH collateral covers 75% of the ETH debt. Excess ETH will be covered by token limit.
// send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100%
uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen
}
function ratios() external view returns (Ratios memory);
function getCurrentExchangePrice()
external
view
returns (
uint256 exchangePrice_,
uint256 newRevenue_
);
function lastRevenueExchangePrice() external view returns (uint256);
function revenueFee() external view returns (uint256);
function revenue() external view returns (uint256);
function revenueEth() external view returns (uint256);
function withdrawalFee() external view returns (uint256);
function idealExcessAmt() external view returns (uint256);
function swapFee() external view returns (uint256);
function saveSlippage() external view returns (uint256);
function totalSupply() external view returns (uint256);
function getVaultBalances()
external
view
returns (
uint256 tokenCollateralAmt_,
uint256 stethCollateralAmt_,
uint256 wethDebtAmt_,
uint256 tokenVaultBal_,
uint256 tokenDSABal_,
uint256 netTokenBal_
);
function getNewProfits()
external
view
returns (uint256 profits_);
function balanceOf(address account) external view returns (uint256);
}
|
TODO: dont take flashloan if not needed
|
function rebalanceTwoData(address vaultAddr_)
public
view
returns (
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 tokenSupplyAmt_
)
{
VaultInterface vault_ = VaultInterface(vaultAddr_);
RebalanceTwoVariables memory v_;
v_.tokenAddr = vault_.token();
v_.tokenDecimals = vault_.decimals();
v_.tokenMinLimit = vault_.tokenMinLimit();
(, v_.stethCollateral, v_.wethDebt, v_.tokenVaultBal,, v_.netTokenBal) = vault_.getVaultBalances();
if (v_.tokenVaultBal > v_.tokenMinLimit) tokenSupplyAmt_ = v_.tokenVaultBal;
VaultInterface.Ratios memory ratios_ = vault_.ratios();
v_.ethCoveringDebt = (v_.stethCollateral * ratios_.stEthLimit) / 10000;
v_.excessDebt = v_.ethCoveringDebt < v_.wethDebt ? v_.wethDebt - v_.ethCoveringDebt : 0;
v_.tokenPriceInEth = IAavePriceOracle(aaveAddressProvider.getPriceOracle()).getAssetPrice(v_.tokenAddr);
v_.netTokenCollateralInEth = (v_.netTokenBal * v_.tokenPriceInEth) / (10 ** v_.tokenDecimals);
v_.currentRatioMax = v_.netTokenCollateralInEth == 0 ? 0 : (v_.excessDebt * 10000) / v_.netTokenCollateralInEth;
if (v_.currentRatioMax > ratios_.maxLimit) {
saveAmt_ = ((v_.currentRatioMax - (ratios_.maxLimitGap + 10)) * v_.netTokenCollateralInEth) / (10000 - ratios_.stEthLimit);
flashTkn_ = wethAddr;
route_ = 5;
}
}
| 6,170,048 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
}
contract AccessControl {
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
address public owner;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/**
* @dev The AccessControl constructor sets the original `owner` of the contract to the sender
* account.
*/
function AccessControl() 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));
owner = newOwner;
}
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused() {
require(paused);
_;
}
/// @dev Called by owner role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyOwner whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called owner.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyOwner whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is AccessControl, 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 whenNotPaused returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract LockableToken is StandardToken, ReentrancyGuard {
struct LockedBalance {
address owner;
uint256 value;
uint256 releaseTime;
}
mapping (uint => LockedBalance) public lockedBalances;
uint public lockedBalanceCount;
event TransferLockedToken(address indexed from, address indexed to, uint256 value, uint256 releaseTime);
event ReleaseLockedBalance(address indexed owner, uint256 value, uint256 releaseTime);
/**
* @dev transfer and lock token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _releaseTime The time to be locked.
*/
function transferLockedToken(address _to, uint256 _value, uint256 _releaseTime) public whenNotPaused nonReentrant returns (bool) {
require(_releaseTime > now);
//require(_releaseTime.sub(1 years) < now);
balances[msg.sender] = balances[msg.sender].sub(_value);
lockedBalances[lockedBalanceCount] = LockedBalance({owner: _to, value: _value, releaseTime: _releaseTime});
lockedBalanceCount++;
emit TransferLockedToken(msg.sender, _to, _value, _releaseTime);
return true;
}
/**
* @dev Gets the locked balance of the specified address.
* @param _owner The address to query the the locked balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function lockedBalanceOf(address _owner) public constant returns (uint256 value) {
for (uint i = 0; i < lockedBalanceCount; i++) {
LockedBalance storage lockedBalance = lockedBalances[i];
if (_owner == lockedBalance.owner) {
value = value.add(lockedBalance.value);
}
}
return value;
}
/**
* @dev Release the locked balance if its releaseTime arrived.
* @return An uint256 representing the amount.
*/
function releaseLockedBalance() public whenNotPaused returns (uint256 releaseAmount) {
uint index = 0;
while (index < lockedBalanceCount) {
if (now >= lockedBalances[index].releaseTime) {
releaseAmount += lockedBalances[index].value;
unlockBalanceByIndex(index);
} else {
index++;
}
}
return releaseAmount;
}
function unlockBalanceByIndex(uint index) internal {
LockedBalance storage lockedBalance = lockedBalances[index];
balances[lockedBalance.owner] = balances[lockedBalance.owner].add(lockedBalance.value);
emit ReleaseLockedBalance(lockedBalance.owner, lockedBalance.value, lockedBalance.releaseTime);
lockedBalances[index] = lockedBalances[lockedBalanceCount - 1];
delete lockedBalances[lockedBalanceCount - 1];
lockedBalanceCount--;
}
}
contract ReleaseableToken is LockableToken {
uint256 public createTime;
uint256 public nextReleaseTime;
uint256 public nextReleaseAmount;
uint256 standardDecimals = 10000;
uint256 public totalSupply;
uint256 public releasedSupply;
function ReleaseableToken(uint256 initialSupply, uint256 initReleasedSupply, uint256 firstReleaseAmount) public {
createTime = now;
nextReleaseTime = now;
nextReleaseAmount = firstReleaseAmount;
totalSupply = standardDecimals.mul(initialSupply);
releasedSupply = standardDecimals.mul(initReleasedSupply);
balances[msg.sender] = standardDecimals.mul(initReleasedSupply);
}
/**
* @dev Release a part of the frozen token(totalSupply - releasedSupply) every 26 weeks.
* @return An uint256 representing the amount.
*/
function release() public whenNotPaused returns(uint256 _releaseAmount) {
require(nextReleaseTime <= now);
uint256 releaseAmount = 0;
uint256 remainderAmount = totalSupply.sub(releasedSupply);
if (remainderAmount > 0) {
releaseAmount = standardDecimals.mul(nextReleaseAmount);
if (releaseAmount > remainderAmount)
releaseAmount = remainderAmount;
releasedSupply = releasedSupply.add(releaseAmount);
balances[owner] = balances[owner].add(releaseAmount);
emit Release(msg.sender, releaseAmount, nextReleaseTime);
nextReleaseTime = nextReleaseTime.add(26 * 1 weeks);
nextReleaseAmount = nextReleaseAmount.sub(nextReleaseAmount.div(4));
}
return releaseAmount;
}
event Release(address receiver, uint256 amount, uint256 releaseTime);
}
contract N2Contract is ReleaseableToken {
string public name = 'N2Chain';
string public symbol = 'N2C';
uint8 public decimals = 4;
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
function N2Contract() public ReleaseableToken(1000000000, 200000000, 200000000) {}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyOwner whenPaused {
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyOwner whenPaused {
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
}
|
Release a part of the frozen token(totalSupply - releasedSupply) every 26 weeks. return An uint256 representing the amount./
|
function release() public whenNotPaused returns(uint256 _releaseAmount) {
require(nextReleaseTime <= now);
uint256 releaseAmount = 0;
uint256 remainderAmount = totalSupply.sub(releasedSupply);
if (remainderAmount > 0) {
releaseAmount = standardDecimals.mul(nextReleaseAmount);
if (releaseAmount > remainderAmount)
releaseAmount = remainderAmount;
releasedSupply = releasedSupply.add(releaseAmount);
balances[owner] = balances[owner].add(releaseAmount);
emit Release(msg.sender, releaseAmount, nextReleaseTime);
nextReleaseTime = nextReleaseTime.add(26 * 1 weeks);
nextReleaseAmount = nextReleaseAmount.sub(nextReleaseAmount.div(4));
}
return releaseAmount;
}
event Release(address receiver, uint256 amount, uint256 releaseTime);
| 13,550,924 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "../libraries/Address.sol";
import "../libraries/SafeMath.sol";
import "../libraries/SafeERC20.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/ITreasury.sol";
import "../types/Ownable.sol";
interface IMasterChef {
function pendingSushi(uint256 _pid, address _user) external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
}
interface ISushiBar {
function enter(uint256 _amount) external;
function leave(uint256 _share) external;
}
/**
* Contract deploys liquidity from treasury into the Onsen program,
* earning $SUSHI that can be staked and/or deposited into the treasury.
*/
contract OnsenAllocator is Ownable {
/* ========== DEPENDENCIES ========== */
using SafeERC20 for IERC20;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
uint256[] public pids; // Pool IDs
mapping(uint256 => address) public pools; // Pool Addresses index by PID
address immutable sushi; // $SUSHI token
address immutable xSushi; // $xSUSHI token
address immutable masterChef; // Onsen contract
address immutable treasury; // Olympus Treasury
uint256 public totalValueDeployed; // Total RFV deployed
/* ========== CONSTRUCTOR ========== */
constructor(
address _chef,
address _treasury,
address _sushi,
address _xSushi
) {
require(_chef != address(0));
masterChef = _chef;
require(_treasury != address(0));
treasury = _treasury;
require(_sushi != address(0));
sushi = _sushi;
require(_xSushi != address(0));
xSushi = _xSushi;
}
/* ========== OPEN FUNCTIONS ========== */
/**
* @notice harvest Onsen rewards from all pools
* @param _stake bool
*/
function harvest(bool _stake) external {
for (uint256 i = 0; i < pids.length; i++) {
uint256 pid = pids[i];
if (pid != 0) {
// pid of 0 is invalid
IMasterChef(masterChef).withdraw(pid, 0); // withdrawing 0 harvests rewards
}
}
enterSushiBar(_stake);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice stake sushi rewards if enter is true. return funds to treasury.
* @param _stake bool
*/
function enterSushiBar(bool _stake) internal {
uint256 balance = IERC20(sushi).balanceOf(address(this));
if (balance > 0) {
if (!_stake) {
IERC20(sushi).safeTransfer(treasury, balance); // transfer sushi to treasury
} else {
IERC20(sushi).approve(xSushi, balance);
ISushiBar(xSushi).enter(balance); // stake sushi
uint256 xBalance = IERC20(xSushi).balanceOf(address(this));
IERC20(xSushi).safeTransfer(treasury, xBalance); // transfer xSushi to treasury
}
}
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice pending $SUSHI rewards
* @return uint
*/
function pendingSushi() external view returns (uint256) {
uint256 pending;
for (uint256 i = 0; i < pids.length; i++) {
uint256 pid = pids[i];
if (pid != 0) {
pending = pending.add(IMasterChef(masterChef).pendingSushi(pid, address(this)));
}
}
return pending;
}
/* ========== POLICY FUNCTIONS ========== */
/**
* @notice deposit LP from treasury to Onsen and collect rewards
* @param _amount uint
* @param _stake bool
*/
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external onlyOwner {
address LP = pools[_pid];
require(LP != address(0));
ITreasury(treasury).manage(LP, _amount); // retrieve LP from treasury
IERC20(LP).approve(masterChef, _amount);
IMasterChef(masterChef).deposit(_pid, _amount); // deposit into Onsen
uint256 value = ITreasury(treasury).tokenValue(LP, _amount);
totalValueDeployed = totalValueDeployed.add(value); // add to deployed value tracker
enterSushiBar(_stake); // manage rewards
}
/**
* @notice collect rewards and withdraw LP from Onsen and return to treasury.
* @param _amount uint
* @param _stake bool
*/
function withdraw(
uint256 _pid,
uint256 _amount,
bool _stake
) external onlyOwner {
address LP = pools[_pid];
require(LP != address(0));
IMasterChef(masterChef).withdraw(_pid, _amount); // withdraw from Onsen
uint256 value = ITreasury(treasury).tokenValue(LP, _amount);
// remove from deployed value tracker
if (value < totalValueDeployed) {
totalValueDeployed = totalValueDeployed.sub(value);
} else {
// LP value grows from fees and may exceed total deployed
totalValueDeployed = 0;
}
// approve and deposit LP into treasury
IERC20(LP).approve(treasury, _amount);
// use value for profit so that no OHM is minted
ITreasury(treasury).deposit(_amount, LP, value);
enterSushiBar(_stake); // manage rewards
}
/**
* @notice withdraw Sushi from treasury and stake to xSushi
* @param _amount uint
*/
function enterSushiBarFromTreasury(uint256 _amount) external onlyOwner {
ITreasury(treasury).manage(sushi, _amount); // retrieve $SUSHI from treasury
enterSushiBar(true); // stake $SUSHI
}
/**
* @notice withdraw xSushi from treasury and unstake to sushi
* @param _amount uint
*/
function exitSushiBar(uint256 _amount) external onlyOwner {
ITreasury(treasury).manage(xSushi, _amount); // retrieve $xSUSHI from treasury
ISushiBar(xSushi).leave(_amount); // unstake $xSUSHI
IERC20(sushi).safeTransfer(treasury, IERC20(sushi).balanceOf(address(this))); // return $SUSHI to treasury
}
/**
* @notice add new PID and corresponding liquidity pool
* @param _pool address
* @param _pid uint
*/
function addPool(address _pool, uint256 _pid) external onlyOwner {
require(_pool != address(0));
require(pools[_pid] == address(0));
pids.push(_pid);
pools[_pid] = _pool;
}
/**
* @notice remove liquidity pool and corresponding PID
* @param _pool address
* @param _index uint
*/
function removePool(address _pool, uint256 _index) external onlyOwner {
uint256 pid = pids[_index];
require(pools[pid] == _pool);
pids[_index] = 0;
pools[pid] = address(0);
}
/**
* @notice withdraw liquidity without regard for rewards
* @param _pid uint
*/
function emergencyWithdraw(uint256 _pid) external onlyOwner {
address LP = pools[_pid];
IMasterChef(masterChef).emergencyWithdraw(_pid); // withdraws LP without returning rewards
uint256 balance = IERC20(LP).balanceOf(address(this));
uint256 value = ITreasury(treasury).tokenValue(LP, balance);
if (value < totalValueDeployed) {
totalValueDeployed = totalValueDeployed.sub(value); // remove from value deployed tracker
} else {
// value increases with fees and would otherwise cause underflow
totalValueDeployed = 0;
}
// approve and deposit LP into treasury
IERC20(LP).approve(treasury, balance);
// use value for profit so that no OHM is minted
ITreasury(treasury).deposit(balance, LP, value);
}
}
|
add new PID and corresponding liquidity pool _pool address _pid uint/
|
function addPool(address _pool, uint256 _pid) external onlyOwner {
require(_pool != address(0));
require(pools[_pid] == address(0));
pids.push(_pid);
pools[_pid] = _pool;
}
| 14,026,014 |
./partial_match/1/0x926C777c091a5A070dC24ac94fF498b5a556f92A/sources/contracts/periphery/SmardexRouter.sol
|
@inheritdoc ISmardexRouter refund dust eth, if any
|
function addLiquidityETH(
AddLiquidityETHParams calldata _params,
address _to,
uint256 _deadline
)
external
payable
virtual
override
ensure(_deadline)
returns (uint256 amountToken_, uint256 amountETH_, uint256 liquidity_)
{
AddLiquidityParams memory _p = AddLiquidityParams({
tokenA: _params.token,
tokenB: WETH,
amountADesired: _params.amountTokenDesired,
amountBDesired: msg.value,
amountAMin: _params.amountTokenMin,
amountBMin: _params.amountETHMin,
fictiveReserveB: _params.fictiveReserveETH,
fictiveReserveAMin: _params.fictiveReserveTokenMin,
fictiveReserveAMax: _params.fictiveReserveTokenMax
});
(amountToken_, amountETH_) = _addLiquidity(_p);
address _pair = PoolAddress.pairFor(factory, _params.token, WETH);
bool _orderedPair = _params.token < WETH;
liquidity_ = ISmardexPair(_pair).mint(
_to,
_orderedPair ? amountToken_ : amountETH_,
_orderedPair ? amountETH_ : amountToken_,
msg.sender
);
if (msg.value > amountETH_) {
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH_);
}
}
| 4,280,003 |
./partial_match/1/0x3B3812BB9f6151bEb6fa10783F1ae848a77a0d46/sources/CollateralErc20.sol
|
scale up before entering the system.
|
function deposit(
address borrower,
uint id,
uint amount
) external {
require(amount <= IERC20(underlyingContract).allowance(msg.sender, address(this)), "Allowance not high enough");
IERC20(underlyingContract).transferFrom(msg.sender, address(this), amount);
uint scaledAmount = scaleUpCollateral(amount);
depositInternal(borrower, id, scaledAmount);
}
| 2,762,253 |
pragma solidity ^0.4.18;
/**
* Ponzi Trust Token Smart Contracts
* Code is published on https://github.com/PonziTrust/Token
* Ponzi Trust https://ponzitrust.com/
*/
import "./SafeMath.sol";
// see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
contract ERC20 {
function name() public view returns (string);
function symbol() public view returns (string);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// see: https://github.com/ethereum/EIPs/issues/677
contract ERC677Token {
function transferAndCall(address receiver, uint amount, bytes data) public returns (bool success);
function contractFallback(address to, uint value, bytes data) internal;
function isContract(address addr) internal view returns (bool hasCode);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
// see: https://github.com/ethereum/EIPs/issues/677
contract ERC677Recipient {
function tokenFallback(address from, uint256 amount, bytes data) public returns (bool success);
}
/**
* @dev The token implement ERC20 and ERC677 standarts(see above).
* use Withdrawal, Restricting Access, State Machine patterns.
* see: http://solidity.readthedocs.io/en/develop/common-patterns.html
* use SafeMath library, see above.
* The owner can intervene in the work of the token only before the expiration
* DURATION_TO_ACCESS_FOR_OWNER = 144 days. Contract has thee state of working:
* 1.PreSale - only owner can access to transfer tokens. 2.Sale - contract to sale
* tokens by func byToken() of fallback, contact and owner can access to transfer tokens.
* Token price setting by owner or price setter. 3.PublicUse - anyone can transfer tokens.
*/
contract PonziToken is ERC20, ERC677Token {
using SafeMath for uint256;
enum State {
PreSale, //PRE_SALE_STR
Sale, //SALE_STR
PublicUse //PUBLIC_USE_STR
}
// we need returns string representation of state
// because enums are not supported by the ABI, they are just supported by Solidity.
// see: http://solidity.readthedocs.io/en/develop/frequently-asked-questions.html#if-i-return-an-enum-i-only-get-integer-values-in-web3-js-how-to-get-the-named-values
string private constant PRE_SALE_STR = "PreSale";
string private constant SALE_STR = "Sale";
string private constant PUBLIC_USE_STR = "PublicUse";
State private m_state;
uint256 private constant DURATION_TO_ACCESS_FOR_OWNER = 144 days;
uint256 private m_maxTokensPerAddress;
uint256 private m_firstEntranceToSaleStateUNIX;
address private m_owner;
address private m_priceSetter;
address private m_bank;
uint256 private m_tokenPriceInWei;
uint256 private m_totalSupply;
uint256 private m_myDebtInWei;
string private m_name;
string private m_symbol;
uint8 private m_decimals;
bool private m_isFixedTokenPrice;
mapping(address => mapping (address => uint256)) private m_allowed;
mapping(address => uint256) private m_balances;
mapping(address => uint256) private m_pendingWithdrawals;
////////////////
// EVENTS
//
event StateChanged(address indexed who, State newState);
event PriceChanged(address indexed who, uint newPrice, bool isFixed);
event TokensSold(uint256 numberOfTokens, address indexed purchasedBy, uint256 indexed priceInWei);
event Withdrawal(address indexed to, uint sumInWei);
////////////////
// MODIFIERS - Restricting Access and State Machine patterns
//
modifier atState(State state) {
require(m_state == state);
_;
}
modifier onlyOwner() {
require(msg.sender == m_owner);
_;
}
modifier onlyOwnerOrAtState(State state) {
require(msg.sender == m_owner || m_state == state);
_;
}
modifier checkAccess() {
require(m_firstEntranceToSaleStateUNIX == 0 // solium-disable-line indentation, operator-whitespace
|| now.sub(m_firstEntranceToSaleStateUNIX) <= DURATION_TO_ACCESS_FOR_OWNER
|| m_state != State.PublicUse
);
_;
// owner has not access if duration To Access For Owner was passed
// and (&&) contract in PublicUse state.
}
modifier validRecipient(address recipient) {
require(recipient != address(0) && recipient != address(this));
_;
}
///////////////
// CONSTRUCTOR
//
/**
* @dev Constructor PonziToken.
*/
function PonziToken() public {
m_owner = msg.sender;
m_bank = msg.sender;
m_state = State.PreSale;
m_decimals = 8;
m_name = "Ponzi";
m_symbol = "PT";
}
/**
* do not forget about:
* https://medium.com/codetractio/a-look-into-paritys-multisig-wallet-bug-affecting-100-million-in-ether-and-tokens-356f5ba6e90a
*
* @dev Initialize the contract, only owner can call and only once.
* @return Whether successful or not.
*/
function initContract()
public
onlyOwner()
returns (bool)
{
require(m_maxTokensPerAddress == 0 && m_decimals > 0);
m_maxTokensPerAddress = uint256(1000).mul(uint256(10)**uint256(m_decimals));
m_totalSupply = uint256(100000000).mul(uint256(10)**uint256(m_decimals));
// 70% for owner
m_balances[msg.sender] = m_totalSupply.mul(uint256(70)).div(uint256(100));
// 30% for sale
m_balances[address(this)] = m_totalSupply.sub(m_balances[msg.sender]);
// allow owner to transfer token from this
m_allowed[address(this)][m_owner] = m_balances[address(this)];
return true;
}
///////////////////
// ERC20 Methods
// get from https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token/ERC20
//
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return m_balances[owner];
}
/**
* @dev The name of the token.
* @return The name of the token.
*/
function name() public view returns (string) {
return m_name;
}
/**
* @dev The symbol of the token.
* @return The symbol of the token.
*/
function symbol() public view returns (string) {
return m_symbol;
}
/**
* @dev The number of decimals the token.
* @return The number of decimals the token.
* @notice Uses - e.g. 8, means to divide the token.
* amount by 100000000 to get its user representation.
*/
function decimals() public view returns (uint8) {
return m_decimals;
}
/**
* @dev Total number of tokens in existence.
* @return Total number of tokens in existence.
*/
function totalSupply() public view returns (uint256) {
return m_totalSupply;
}
/**
* @dev Transfer token for a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return Whether successful or not.
*/
function transfer(address to, uint256 value)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(to)
returns (bool)
{
// require(value <= m_balances[msg.sender]);
// SafeMath.sub will already throw if this condition is not met
m_balances[msg.sender] = m_balances[msg.sender].sub(value);
m_balances[to] = m_balances[to].add(value);
Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from Address The address which you want to send tokens from.
* @param to Address The address which you want to transfer to.
* @param value Uint256 the amount of tokens to be transferred.
* @return Whether successful or not.
*/
function transferFrom(address from, address to, uint256 value)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(to)
returns (bool)
{
// require(value <= m_balances[from]);
// require(value <= m_allowed[from][msg.sender]);
// SafeMath.sub will already throw if this condition is not met
m_balances[from] = m_balances[from].sub(value);
m_balances[to] = m_balances[to].add(value);
m_allowed[from][msg.sender] = m_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.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return Whether successful or not.
*/
function approve(address spender, uint256 value)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(spender)
returns (bool)
{
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((value == 0) || (m_allowed[msg.sender][spender] == 0));
m_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 m_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.
*
* @dev Increase the amount of tokens that an owner allowed to a spender.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
* @return Whether successful or not.
*/
function increaseApproval(address spender, uint addedValue)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(spender)
returns (bool)
{
m_allowed[msg.sender][spender] = m_allowed[msg.sender][spender].add(addedValue);
Approval(msg.sender, spender, m_allowed[msg.sender][spender]);
return true;
}
/**
* Approve should be called when allowed[spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol.
*
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
* @return Whether successful or not.
*/
function decreaseApproval(address spender, uint subtractedValue)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(spender)
returns (bool)
{
uint oldValue = m_allowed[msg.sender][spender];
if (subtractedValue > oldValue) {
m_allowed[msg.sender][spender] = 0;
} else {
m_allowed[msg.sender][spender] = oldValue.sub(subtractedValue);
}
Approval(msg.sender, spender, m_allowed[msg.sender][spender]);
return true;
}
///////////////////
// ERC677 Methods
//
/**
* @dev Transfer token to a contract address with additional data if the recipient is a contact.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @param extraData The extra data to be passed to the receiving contract.
* @return Whether successful or not.
*/
function transferAndCall(address to, uint256 value, bytes extraData)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(to)
returns (bool)
{
// require(value <= m_balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
m_balances[msg.sender] = m_balances[msg.sender].sub(value);
m_balances[to] = m_balances[to].add(value);
Transfer(msg.sender, to, value);
if (isContract(to)) {
contractFallback(to, value, extraData);
Transfer(msg.sender, to, value, extraData);
}
return true;
}
/**
* @dev transfer token all tokens to a contract address with additional data if the recipient is a contact.
* @param to The address to transfer all to.
* @param extraData The extra data to be passed to the receiving contract.
* @return Whether successful or not.
*/
function transferAllAndCall(address to, bytes extraData)
external
onlyOwnerOrAtState(State.PublicUse)
returns (bool)
{
return transferAndCall(to, m_balances[msg.sender], extraData);
}
/**
* @dev Call ERC677 tokenFallback for ERC677Recipient contract.
* @param to The address of ERC677Recipient.
* @param value Amount of tokens with was sended
* @param data Sended to ERC677Recipient.
* @return Whether contract or not.
*/
function contractFallback(address to, uint value, bytes data)
internal
{
ERC677Recipient recipient = ERC677Recipient(to);
recipient.tokenFallback(msg.sender, value, data);
}
/**
* @dev Check addr if is contract.
* @param addr The address that checking.
* @return Whether contract or not.
*/
function isContract(address addr) internal view returns (bool) {
uint length;
assembly { length := extcodesize(addr) }
return length > 0;
}
///////////////////
// payable Methods
// use withdrawal pattern
// see: http://solidity.readthedocs.io/en/develop/common-patterns.html#withdrawal-from-contracts
// see: https://consensys.github.io/smart-contract-best-practices/known_attacks/
//
/**
* Recived ETH converted to tokens amount for price. sender has max limit for tokens
* amount as m_maxTokensPerAddress - balanceOf(sender). if amount <= max limit
* then transfer amount from this to sender and 95%ETH to bank, 5%ETH to owner.
* else amount > max limit then we calc cost of max limit of tokens,
* store this cost in m_pendingWithdrawals[sender] and m_myDebtInWei and
* transfer max limit of tokens from this to sender and 95% max limit cost to bank
* 5% max limit cost to owner.
*
* @dev Contract receive ETH (payable) from sender and transfer some amount of tokens to him.
*/
function byTokens() public payable atState(State.Sale) {
// check if msg.sender can to by tokens
require(m_balances[msg.sender] < m_maxTokensPerAddress);
// get actual token price and set it
m_tokenPriceInWei = calcTokenPriceInWei();
// check if msg.value has enough for by 1 token
require(msg.value >= m_tokenPriceInWei);
// calc max available tokens for sender
uint256 maxAvailableTokens = m_maxTokensPerAddress.sub(m_balances[msg.sender]);
// convert msg.value(wei) to tokens
uint256 tokensAmount = weiToTokens(msg.value, m_tokenPriceInWei);
if (tokensAmount > maxAvailableTokens) {
// we CANT transfer all tokens amount, ONLY max available tokens
// calc cost in wei of max available tokens
// subtract cost from msg.value and store it as debt for sender
tokensAmount = maxAvailableTokens;
// calc cost
uint256 tokensAmountCostInWei = tokensToWei(tokensAmount, m_tokenPriceInWei);
// calc debt
uint256 debt = msg.value.sub(tokensAmountCostInWei);
// Withdrawal pattern avoid Re-Entrancy (dont use transfer to unknow address)
// update pending withdrawals
m_pendingWithdrawals[msg.sender] = m_pendingWithdrawals[msg.sender].add(debt);
// update my debt
m_myDebtInWei = m_myDebtInWei.add(debt);
}
// transfer tokensAmount tokens form this to sender
// SafeMath.sub will already throw if this condition is not met
m_balances[address(this)] = m_balances[address(this)].sub(tokensAmount);
m_balances[msg.sender] = m_balances[msg.sender].add(tokensAmount);
// we can transfer eth to owner and bank, because we know that they
// dont use Re-Entrancy and other attacks.
// transfer 5% of eht-myDebt to owner
// owner cant be equal address(0) because this function to be accessible
// only in State.Sale but owner can be equal address(0), only in State.PublicUse
// State.Sale not equal State.PublicUse!
m_owner.transfer(this.balance.sub(m_myDebtInWei).mul(uint256(5)).div(uint256(100)));
// transfer 95% of eht-myDebt to bank
// bank cant be equal address(0) see setBank() and PonziToken()
m_bank.transfer(this.balance.sub(m_myDebtInWei));
checkValidityOfBalance(); // this.balance >= m_myDebtInWei
Transfer(address(this), msg.sender, tokensAmount);
TokensSold(tokensAmount, msg.sender, m_tokenPriceInWei);
}
/**
* @dev Sender receive his pending withdrawals(if > 0).
*/
function withdraw() external {
uint amount = m_pendingWithdrawals[msg.sender];
require(amount > 0);
// set zero the pending refund before
// sending to prevent Re-Entrancy
m_pendingWithdrawals[msg.sender] = 0;
m_myDebtInWei = m_myDebtInWei.sub(amount);
msg.sender.transfer(amount);
checkValidityOfBalance(); // this.balance >= m_myDebtInWei
Withdrawal(msg.sender, amount);
}
/**
* @notice http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function
* we dont need recieve ETH always, only in State.Sale from externally accounts.
*
* @dev Fallback func, call byTokens().
*/
function() public payable atState(State.Sale) {
byTokens();
}
////////////////////////
// external view methods
// everyone outside has access
//
/**
* @dev Gets the pending withdrawals of the specified address.
* @param owner The address to query the pending withdrawals of.
* @return An uint256 representing the amount withdrawals owned by the passed address.
*/
function pendingWithdrawals(address owner) external view returns (uint256) {
return m_pendingWithdrawals[owner];
}
/**
* @dev Get contract work state.
* @return Contract work state via string.
*/
function state() external view returns (string stateString) {
if (m_state == State.PreSale) {
stateString = PRE_SALE_STR;
} else if (m_state == State.Sale) {
stateString = SALE_STR;
} else if (m_state == State.PublicUse) {
stateString = PUBLIC_USE_STR;
}
}
/**
* @dev Get price of one token in wei.
* @return Price of one token in wei.
*/
function tokenPriceInWei() public view returns (uint256) {
return calcTokenPriceInWei();
}
/**
* @dev Get address of the bank.
* @return Address of the bank.
*/
function bank() external view returns(address) {
return m_bank;
}
/**
* @dev Get timestamp of first entrance to sale state.
* @return Timestamp of first entrance to sale state.
*/
function firstEntranceToSaleStateUNIX()
external
view
returns(uint256)
{
return m_firstEntranceToSaleStateUNIX;
}
/**
* @dev Get address of the price setter.
* @return Address of the price setter.
*/
function priceSetter() external view returns (address) {
return m_priceSetter;
}
////////////////////
// public methods
// only for owner
//
/**
* @dev Owner do disown.
*/
function disown() external atState(State.PublicUse) onlyOwner() {
delete m_owner;
}
/**
* @dev Set state of contract working.
* @param newState String representation of new state.
*/
function setState(string newState)
external
onlyOwner()
checkAccess()
{
if (keccak256(newState) == keccak256(PRE_SALE_STR)) {
m_state = State.PreSale;
} else if (keccak256(newState) == keccak256(SALE_STR)) {
if (m_firstEntranceToSaleStateUNIX == 0)
m_firstEntranceToSaleStateUNIX = now;
m_state = State.Sale;
} else if (keccak256(newState) == keccak256(PUBLIC_USE_STR)) {
m_state = State.PublicUse;
} else {
// if newState not valid string
revert();
}
StateChanged(msg.sender, m_state);
}
/**
* If token price not fix then actual price
* always will be tokenPriceInWeiForDay(day).
*
* @dev Set price of one token in wei and fix it.
* @param newTokenPriceInWei Price of one token in wei.
*/
function setAndFixTokenPriceInWei(uint256 newTokenPriceInWei)
external
checkAccess()
{
require(msg.sender == m_owner || msg.sender == m_priceSetter);
m_isFixedTokenPrice = true;
m_tokenPriceInWei = newTokenPriceInWei;
PriceChanged(msg.sender, m_tokenPriceInWei, m_isFixedTokenPrice);
}
/**
* If token price is unfixed then actual will be tokenPriceInWeiForDay(day).
*
* @dev Set unfix token price to true.
*/
function unfixTokenPriceInWei()
external
checkAccess()
{
require(msg.sender == m_owner || msg.sender == m_priceSetter);
m_isFixedTokenPrice = false;
PriceChanged(msg.sender, m_tokenPriceInWei, m_isFixedTokenPrice);
}
/**
* @dev Set the PriceSetter address, which has access to set one token price in wei.
* @param newPriceSetter The address of new PriceSetter.
*/
function setPriceSetter(address newPriceSetter)
external
onlyOwner()
checkAccess()
{
m_priceSetter = newPriceSetter;
}
/**
* @dev Set the bank, which receive 95%ETH from tokens sale.
* @param newBank The address of new bank.
*/
function setBank(address newBank)
external
validRecipient(newBank)
onlyOwner()
checkAccess()
{
require(newBank != address(0));
m_bank = newBank;
}
////////////////////////
// internal pure methods
//
/**
* @dev Convert token to wei.
* @param tokensAmount Amout of tokens.
* @param tokenPrice One token price in wei.
* @return weiAmount Result amount of convertation.
*/
function tokensToWei(uint256 tokensAmount, uint256 tokenPrice)
internal
pure
returns(uint256 weiAmount)
{
weiAmount = tokensAmount.mul(tokenPrice);
}
/**
* @dev Conver wei to token.
* @param weiAmount Wei amout.
* @param tokenPrice One token price in wei.
* @return tokensAmount Result amount of convertation.
*/
function weiToTokens(uint256 weiAmount, uint256 tokenPrice)
internal
pure
returns(uint256 tokensAmount)
{
tokensAmount = weiAmount.div(tokenPrice);
}
////////////////////////
// private view methods
//
/**
* @dev Get actual token price.
* @return price One token price in wei.
*/
function calcTokenPriceInWei()
private
view
returns(uint256 price)
{
if (m_isFixedTokenPrice) {
// price is fixed, return current val
price = m_tokenPriceInWei;
} else {
// price not fixed, we must to calc price
if (m_firstEntranceToSaleStateUNIX == 0) {
// if contract dont enter to SaleState then price = 0
price = 0;
} else {
// calculate day after first Entrance To Sale State
uint256 day = now.sub(m_firstEntranceToSaleStateUNIX).div(1 days);
// use special formula for calcutation price
price = tokenPriceInWeiForDay(day);
}
}
}
/**
* @dev Get token price for specific day after starting sale tokens.
* @param day Secific day.
* @return price One token price in wei for specific day.
*/
function tokenPriceInWeiForDay(uint256 day)
private
view
returns(uint256 price)
{
// day 1: price 1*10^(decimals) TOKEN = 0.001 ETH
// price 1 TOKEN = 1 * 10^(-3) ETH / 10^(decimals), in ETH
// convert to wei:
// price 1 TOKEN = 1 * 10^(-3) * wei * 10^(-decimals)
// price 1 TOKEN = 1 * 10^(-3) * 10^(18) * 10^(-decimals)
// price 1 TOKEN = 1 * 10^(15) * 10^(-decimals), in WEI
// day 2: price 1*10^(decimals) TOKEN = 0.002 ETH;
// price 1 TOKEN = 2 * 10^(15) * 10^(-decimals), in WEI
// ...
// day 12: price 1*10^(decimals) TOKEN = 0.012 ETH;
// price 1 TOKEN = 12 * 10^(15) * 10^(-decimals), in WEI
// day >12: price 1*10^(decimals) TOKEN = 0.012 ETH;
// price 1 TOKEN = 12 * 10^(15) * 10^(-decimals), in WEI
// from 0 to 11 - sum is 12 days
if (day <= 11)
price = day.add(1);// because from >0h to <24h after start day will be 0,
else // but for calc price it must be 1;
price = 12;
// convert to WEI
price = price.mul(uint256(10**15)).div(10**uint256(m_decimals));
}
/**
* @notice It is always must be true, for correct withdrawals and receivers ETH.
*
* Check if this.balance >= m_myDebtInWei.
*/
function checkValidityOfBalance() private view {
// assertion is not a strict equality of the balance because the contract
// can be forcibly sent ether without going through the byTokens() func.
// selfdestruct does not trigger a contract's fallback function.
// see: http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function
assert(this.balance >= m_myDebtInWei);
}
}
|
Set state of contract working. newState String representation of new state./ if newState not valid string
|
function setState(string newState)
external
onlyOwner()
checkAccess()
{
if (keccak256(newState) == keccak256(PRE_SALE_STR)) {
m_state = State.PreSale;
if (m_firstEntranceToSaleStateUNIX == 0)
m_firstEntranceToSaleStateUNIX = now;
m_state = State.Sale;
m_state = State.PublicUse;
revert();
}
StateChanged(msg.sender, m_state);
}
| 957,273 |
pragma solidity 0.4.24;
contract SmartContractTest {
function multiplyWithSeven (uint256 a) public pure returns(uint) {
return a * 7;
}
// uint, int: synonyms for uint256, int256 respectively (not to be used for computing the function selector).
function multiplyWithSevenUsingAlias (uint a) public pure returns(uint) {
return a * 7;
}
}
|
uint, int: synonyms for uint256, int256 respectively (not to be used for computing the function selector).
|
function multiplyWithSevenUsingAlias (uint a) public pure returns(uint) {
return a * 7;
}
| 993,583 |
pragma solidity ^0.5.0;
import "./GameToken.sol";
import "./DrawToken.sol";
contract Tetris{
address payable public owner;
bool isFinished = false;
address cel;
uint private max=5;//이 인원이 꽉차면 roleVoting이 돌아간다.
mapping(address=>bool) blockUser;
mapping(address=>uint) userCounts; //각 유저의 누적점수를 올리기 위한 용도
mapping(address=>uint) gameCheck;
address[2] tokenAddress;//토큰 컨트랙의 어드레스를 받아서 함수를 시행시킬 변수이다.
//스마트컨트랙(스마트컨트랙주소)를하면 배포한 스마트 컨트랙트를 사용할수 있다.
address[] votingAddress;
uint private lockMoney=0;
uint private lockMoney2=0;
uint private time=0;
uint firstBlock;
uint secondBlock;
event CheckScores(uint scores);//자신의 누적점수 보기
event checkHouseEther(uint house); //하우스에 저장된 이더 보기
event etherToGameToken(uint house,uint myEther); //이더리움을 이용해서 GameToken을 구매한 경우 보기
event checkToken(address gameToken); //GameToken, Draw토큰 컨트랙트 주소 보기
event checkToken2(address drawToken); //GameToken, Draw토큰 컨트랙트 주소 보기
event gameTokenTodrawToken(uint myGametoken, uint myDrawtoken);
event drawToether(uint myehter);
event resultVoting();
event failVoting(string result);
event congrat(address receiver); //당첨자의 주소를 return 시킨다.
event checkArgument(address[] output,uint firstBlocknumber, uint secondBlocknumber);//주소를 리턴시킨다.
event Score(string tem); //시간이 1분 미만이라 누적점수 얻는 것을 실패한 event
event attendResult(uint index); //응모에 참여했을 때, 몇번째 배열인지 확인시켜주는 용도
event useGameItem(bool result); //게임아이템을 사용했을 때 사용 용도
constructor () public {
owner = msg.sender; //컨트랙트를 배포하는 사람을 owner로 정의한다.
tokenAddress[0] = address(new GameToken(msg.sender)); //이 스마트 컨트랙을 배포한 사람한테 토큰도 같이
//배포 시키고 전체 이더를 준다. tokenAddress에 스마트 컨트랙 주소를 저장시킨다.
tokenAddress[1] = address(new DrawToken(msg.sender));
}
modifier onlyOwner {
require (msg.sender == owner, "Tetris:Only owner can call this function.");
_;
}
function example(address to, uint amount)external {
GameToken(tokenAddress[0]).transfer(to,amount);
//이런식으로 다른 스마트 컨트랙트의 함수를 사용한다.
}
function checkTokenAddress() external{
emit checkToken(tokenAddress[0]);
}
function checkTokenAddress2() external{
emit checkToken2(tokenAddress[1]);
}
function checkMyToken() external{
uint game = GameToken(tokenAddress[0]).balanceOf(msg.sender);
uint draw = DrawToken(tokenAddress[1]).balanceOf(msg.sender);
emit etherToGameToken(game, draw);
}
function buyDrawToken(uint16 gameToken, uint16 drawToken) external payable{
//gameToken을 사용해서 drawToken을 사야한다.
uint myGameToken = GameToken(tokenAddress[0]).balanceOf(msg.sender);
require(myGameToken > gameToken,"Tetris: you dont have that much gameToken");
uint HouseDrawToken = lockMoney2; //하우스의 draw 토큰을 가져옴
require(HouseDrawToken > drawToken,"Tetris: Sorry, House Ether is lack of your request");
//게임토큰을 다시 보내고 추첨토큰을 가져와야한다.
if(GameToken(tokenAddress[0]).transfer2(msg.sender,gameToken)){
//게임 토큰 보냄
DrawToken(tokenAddress[1]).getDrawToken(msg.sender,drawToken);
lockMoney2 -= drawToken;
lockMoney += gameToken;
uint gameT = GameToken(tokenAddress[0]).balanceOf(msg.sender);
uint drawT = DrawToken(tokenAddress[1]).balanceOf(msg.sender);
emit gameTokenTodrawToken(gameT, drawT);
}
}
function startGame() external{//여기에서 유저가 게임을 시작하면 그 유저의 주소에 현재 시간을 저장시킨다.
if(blockUser[msg.sender]==false){
gameCheck[msg.sender] = block.timestamp;
blockUser[msg.sender] = true;
}else if(block.timestamp -gameCheck[msg.sender] > 3 minutes ){
gameCheck[msg.sender] = now;
blockUser[msg.sender] = true;
}
}
function reFundEther(uint drawToken)external payable{
//drawtoken으로 ether로 환불하기
//먼저 컨트랙트 내에 ether가 얼마 있는지부터 확인
uint myEther = address(this).balance;
require(myEther > drawToken,"Tetris: in contract, we don't have enough ether");
//스마트 컨트랙 돈이 더 많으니 이제 보내야한다.
uint myEther2 = DrawToken(tokenAddress[1]).balanceOf(msg.sender);
require(myEther2> drawToken,"Tetris: you don't have that much drawToken");
if(DrawToken(tokenAddress[1]).transferFrom(msg.sender,owner,drawToken)){
lockMoney2 += drawToken;
msg.sender.transfer(drawToken);// 컨트랙트 내의 돈을 전달
emit drawToether(myEther2-drawToken);//기존의 drawToken에다가 -해서 보여준다.
}
}
function getGameToken() external{
//누적점수를 이용해서 게임 토큰을 얻는다.
require(userCounts[msg.sender]>5,"Tetris: you dont have enough scores!");
if(GameToken(tokenAddress[0]).Token(msg.sender,1)){
lockMoney--;
userCounts[msg.sender] -= 5;
}
}
function buyGameToken()external payable{
//여기서 GameToken을 사야함.
uint amount = msg.value;
require(amount < lockMoney,"Tetris: your ether is larger than house money");
if(GameToken(tokenAddress[0]).Token(msg.sender,amount)){
lockMoney -= amount;
uint myEther = GameToken(tokenAddress[0]).balanceOf(msg.sender);
emit etherToGameToken(lockMoney,myEther);//이더리움을 이용해서 Game이더 구입
//넘겨온 이더는 컨트랙트에 있음
}
}
function attendVoting()external {
//사용자가 추첨에 지원하는 것
//DRAW 토큰을 하나 써야함
if(isFinished==true){
isFinished=false;
votingAddress.length=0;
}
uint256 pos = 0;
isFinished = false;
if(DrawToken(tokenAddress[1]).useToken(msg.sender)){
//voting 배열에 지원자를 추가함.
pos = votingAddress.push(msg.sender); //배열에 추가시킨다.
if(pos==max-1){
firstBlock=block.number;
}
if(pos==max){
roleVoting();
}
emit attendResult(pos);
//pos가 원래 정한 위치의 숫자라면 그 주소의 값을 해쉬값에 추가시킨다.
}else{//돈이 없어서 실패
emit resultVoting();
}
}
function roleVoting() private {
//추첨을 돌리는 함수 다 하고 나면 배열을 초기화 시킨다.
secondBlock = block.number;
bytes32 random = keccak256(abi.encodePacked(blockhash(secondBlock),blockhash(firstBlock)));
uint len = uint(random)%votingAddress.length;
isFinished=true;
cel=votingAddress[len];
//cel은 당첨자의 주소를 저장시킨다.
emit congrat(votingAddress[len]);
}
function checkArg() external{
//인자값으로 넣은 주소를 보여준다.
if(isFinished){
emit checkArgument(votingAddress,firstBlock,secondBlock);//인덱스에 들어간 주소를 전부 리턴시켜야 한다.
}else{
emit failVoting("아직 응모가 종료되지 않았습니다.");
//새롭게 시작해서 확인못한다고 해야 한다.
}
}
function charging(uint scores)external onlyOwner payable{ //배포자로부터 스마트컨드랙트에 이더를 받는다.
require(owner==msg.sender,"Only owner can charge ether");
if(GameToken(tokenAddress[0]).charging(scores)){
lockMoney += scores;
uint myEther = GameToken(tokenAddress[0]).balanceOf(msg.sender);
emit etherToGameToken(lockMoney, myEther);
}
//HanyangToken을 충전하는 이더
}
function charging2(uint scores)external onlyOwner payable{ //배포자로부터 스마트컨드랙트에 이더를 받는다.
require(owner==msg.sender,"Only owner can charge ether");
if(DrawToken(tokenAddress[1]).charging(scores)){
lockMoney2 += scores;
uint myEther = DrawToken(tokenAddress[0]).balanceOf(msg.sender);
emit etherToGameToken(lockMoney2, myEther);
}
}
function win(uint scores)public{
//payable은 함수가 이더를 받아야할때 사용된다.
//msg.value는 이 함수로 넘어온 이더를 뜻하고
//address.send(amount); 는 address로 돈을 보내는것을 뜻한다.
//event를 사용해서 인자를 넘기면 front end에서는 args를 통해 인자를 사용할수 있다.
if(blockUser[msg.sender]==true){
blockUser[msg.sender] = false;
if(1 minutes < block.timestamp - gameCheck[msg.sender]){
//유저가 게임을 시작한 시간과 끝낸 시간이 1분보다 크면 무조건 주게 된다.
require(0<scores,"your scores did not satisfy standardPoint");
userCounts[msg.sender]++; //기준점수 이상 달성했으면 이 유저의 주소에 누적점수 1 추가
if(userCounts[msg.sender]>9){
//GameToken에서 토큰을 추가 발행한다.
lockMoney++;//lockMoney가 스마트 컨트랙트가 가진 gametoken의 량이다.
time++;
GameToken(tokenAddress[0]).makeToken();
if(time&10==0){
//10번 게임토큰을 생성할때마다 DrawToken도 추가한다.
lockMoney2++;
DrawToken(tokenAddress[1]).makeToken();
}
}
emit Score("게임 이용 시간이 1분 이상이고 누적점수 얻는 것에 성공하였습니다!");
}else{
emit Score("게임이용시간이 1분 미만이기에 누적점수 얻기에 실패하였습니다.");
//게임시작시간과 종료시간이 1분이 안되었기에 실패한다.
}
//여기서 이제 더해도 응모권을 못얻는다는 event 발생
}
}
// Funds withdrawal to maintain the house
// 이 컨트랙에서 이더를 인출하는 메소드, 오직 owner만 해야한다
function getEther(uint money)external{
//누적점수를 이용해서 이더를 받는 스마트컨트랙.
require(lockMoney > money,"we don't have enough ether");
require(userCounts[msg.sender] > money, "you are not entitled"); //함수를 호출한 유저의 주소
userCounts[msg.sender] -= money; //충전한것만큼 점수를 뺀다.
lockMoney -= money;
GameToken(tokenAddress[0]).Token(msg.sender, money);
//하우스 이더에서 사용자한테 간다. 배포자가 보내는건 ㄴㄴ
}
function check()external{ //자신의 누적점수를 보고싶을때 누른다.
uint he = userCounts[msg.sender];
emit CheckScores(he);
}
function checkMyGameToken() external{
uint myEther = GameToken(tokenAddress[0]).balanceOf(msg.sender);
emit etherToGameToken(lockMoney, myEther);
}
function checkHouse()external{ //배포가자 컨트랙트에 저장시킨 이더를 확인시켜준다.
uint he;
he = lockMoney;
emit checkHouseEther(he);
}
function checkHouse2()external{ //배포가자 컨트랙트에 저장시킨 이더를 확인시켜준다.
uint he;
he = lockMoney2;
emit checkHouseEther(he);
}
function useItem()external {
//hanyang token으로 아이템을 사용한다.
uint myEther = GameToken(tokenAddress[0]).balanceOf(msg.sender);
bool result = false;
if(myEther>=1){
bool result = GameToken(tokenAddress[0]).charging(1);
lockMoney++;
}else{
bool result = false;
}
emit useGameItem(result);
}
function kill() external onlyOwner {
selfdestruct(owner);
}
function () external payable {} //fallback 함수 . 이 컨트랙트가 배포될때 하우스의 초기운영자금이 저장되기 위해 만듬
}
|
누적점수를 이용해서 이더를 받는 스마트컨트랙.하우스 이더에서 사용자한테 간다. 배포자가 보내는건 ㄴㄴ
|
function getEther(uint money)external{
require(lockMoney > money,"we don't have enough ether");
lockMoney -= money;
GameToken(tokenAddress[0]).Token(msg.sender, money);
}
| 12,647,671 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "./library/DateTime.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}.
*
* 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 AOC_ERC20 is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, OwnableUpgradeable, PausableUpgradeable, UUPSUpgradeable {
using DateTimeLibrary for uint;
struct Level {
uint256 start;
uint256 end;
uint256 percentage;
}
struct UserInfo {
uint256 balance;
uint256 level;
uint256 year;
uint256 month;
}
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public blacklisted;
mapping (address => bool) public excludedFromRAMS;
mapping (address => bool) public includedInLTAF;
mapping(uint256 => Level) public levels;
mapping(address => UserInfo) public userInfo;
uint256 private _totalSupply;
uint8 private constant _decimal = 18;
string private constant _name = "Alpha Omega Coin";
string private constant _symbol = "AOC";
uint256 public ltafPercentage;
event ExternalTokenTransfered(
address from,
address to,
uint256 amount
);
event ETHFromContractTransferred(
uint256 amount
);
event Blacklisted(
string indexed action,
address indexed to,
uint256 at
);
event RemovedFromBlacklist(
string indexed action,
address indexed to,
uint256 at
);
event IncludedInRAMS(
address indexed account
);
event ExcludedFromRAMS(
address indexed account
);
event IncludedInLTAF(
address indexed account
);
event ExcludedFromLTAF(
address indexed account
);
event LtafPercentageUpdated(
uint256 percentage
);
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function initialize() public initializer {
_mint(_msgSender(), (1000 * 10**8 * 10**18)); //mint the initial total supply
ltafPercentage = 60;
addLevels(1, 1640995200, 1704153599, 20);
addLevels(2, 1704153600, 1767311999, 15);
addLevels(3, 1767312000, 1830383999, 10);
addLevels(4, 1830384000, 0, 5);
// initializing
__Pausable_init_unchained();
__Ownable_init_unchained();
__Context_init_unchained();
}
function _authorizeUpgrade(address) internal override onlyOwner {}
/**
* @dev Returns the name of the token.
*/
function name() external view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external 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() external view virtual override returns (uint8) {
return _decimal;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) external 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) external virtual override whenNotPaused returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) external 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) external virtual override whenNotPaused 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) external virtual override whenNotPaused returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external virtual whenNotPaused 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) external virtual whenNotPaused returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external virtual onlyOwner whenNotPaused returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) external virtual onlyOwner whenNotPaused {
uint256 currentAllowance = _allowances[account][_msgSender()];
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
function blacklistUser(address _address) external onlyOwner whenNotPaused {
require(!blacklisted[_address], "User is already blacklisted");
blacklisted[_address] = true;
emit Blacklisted("Blacklisted", _address, block.timestamp);
}
function removeFromBlacklist(address _address) external onlyOwner whenNotPaused {
require(blacklisted[_address], "User is not in the blacklist");
blacklisted[_address] = false;
emit RemovedFromBlacklist("Removed", _address, block.timestamp);
}
function includeInRAMS(address account) external onlyOwner whenNotPaused {
require(excludedFromRAMS[account], "User is already included");
excludedFromRAMS[account] = false;
emit IncludedInRAMS(account);
}
function excludeFromRAMS(address account) external onlyOwner whenNotPaused {
require(!excludedFromRAMS[account], "User is already excluded");
excludedFromRAMS[account] = true;
emit ExcludedFromRAMS(account);
}
function includeInLTAF(address account) external onlyOwner whenNotPaused {
require(!includedInLTAF[account], "User is already included");
includedInLTAF[account] = true;
emit IncludedInLTAF(account);
}
function excludedFromLTAF(address account) external onlyOwner whenNotPaused {
require(includedInLTAF[account], "User is already excluded");
includedInLTAF[account] = false;
emit ExcludedFromLTAF(account);
}
function updateLtafPercentage(uint256 percentage) external onlyOwner whenNotPaused {
require(percentage > 0, "Percentage must be greater than zero");
ltafPercentage = percentage;
emit LtafPercentageUpdated(ltafPercentage);
}
/**
* @dev Pause `contract` - pause events.
*
* See {ERC20Pausable-_pause}.
*/
function pauseContract() external virtual onlyOwner {
_pause();
}
/**
* @dev Pause `contract` - pause events.
*
* See {ERC20Pausable-_pause}.
*/
function unPauseContract() external virtual onlyOwner {
_unpause();
}
function withdrawETHFromContract(address payable recipient, uint256 amount) external onlyOwner payable {
require(recipient != address(0), "Address cant be zero address");
require(amount <= address(this).balance, "withdrawETHFromContract: withdraw amount exceeds ETH balance");
recipient.transfer(amount);
emit ETHFromContractTransferred(amount);
}
function withdrawToken(address _tokenContract, uint256 _amount) external onlyOwner {
require(_tokenContract != address(0), "Address cant be zero address");
// require amount greter than 0
require(_amount > 0, "amount cannot be 0");
IERC20Upgradeable tokenContract = IERC20Upgradeable(_tokenContract);
require(tokenContract.balanceOf(address(this)) > _amount, "withdrawToken: withdraw amount exceeds token balance");
tokenContract.transfer(msg.sender, _amount);
emit ExternalTokenTransfered(_tokenContract, msg.sender, _amount);
}
// to recieve ETH
receive() external payable {}
/**
* @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(!blacklisted[sender] || !blacklisted[recipient], "AOC: Cant't transfer, User is blacklisted");
require(sender != address(0), "AOC: transfer from the zero address");
require(recipient != address(0), "AOC: transfer to the zero address");
if(includedInLTAF[sender] || !excludedFromRAMS[sender]) {
// convert current timestamp to uint256
(uint256 year, uint256 month, uint256 day) = DateTimeLibrary.timestampToDate(block.timestamp);
if(day == 1 || year != userInfo[sender].year || month != userInfo[sender].month || userInfo[sender].level == 0) updateUserInfo(sender, year, month);
if(includedInLTAF[sender]) {
// validate amount
require(amount <= ((userInfo[sender].balance * ltafPercentage) / 10**2), "ERC20: Amount is higher than LTAF percentage");
} else if(!excludedFromRAMS[sender]) {
// validate amount
if(userInfo[sender].level > 0) require(amount <= ((userInfo[sender].balance * levels[userInfo[sender].level].percentage) / 10**2), "ERC20: Amount is higher");
}
}
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function updateUserInfo(address account, uint256 year, uint256 month) internal {
userInfo[account].balance = _balances[account];
userInfo[account].year = year;
userInfo[account].month = month;
for(uint256 i = 1; i <= 4; i++) {
if(i == 4) {
userInfo[account].level = i;
break;
}
if(block.timestamp >= levels[i].start && block.timestamp <= levels[i].end) {
userInfo[account].level = i;
break;
}
}
}
/** @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");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function addLevels(uint256 level, uint256 startDay, uint256 endDay, uint256 percentage) internal {
levels[level] = Level({
start: startDay,
end: endDay,
percentage: percentage
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library DateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
int constant OFFSET19700101 = 2440588;
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
|
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");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
| 456,099 |
/*
___ _ ___ _
| .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___
| _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._>
|_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___.
* PeriFinance: EtherCollateral.sol
*
* Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/EtherCollateral.sol
* Docs: Will be added in the future.
* https://docs.peri.finance/contracts/source/contracts/EtherCollateral
*
* Contract Dependencies:
* - IAddressResolver
* - IEtherCollateral
* - MixinResolver
* - Owned
* - Pausable
* - ReentrancyGuard
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 PeriFinance
*
* 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
*/
pragma solidity 0.5.16;
// https://docs.peri.finance/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// Inheritance
// https://docs.peri.finance/contracts/source/contracts/pausable
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
constructor() internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
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, "ReentrancyGuard: reentrant call");
}
}
// https://docs.peri.finance/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getPynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.peri.finance/contracts/source/interfaces/ipynth
interface IPynth {
// Views
function currencyKey() external view returns (bytes32);
function transferablePynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to PeriFinance
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function canBurnPynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function externalTokenLimit() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function externalTokenQuota(
address _account,
uint _addtionalpUSD,
uint _addtionalExToken,
bool _isIssue
) external view returns (uint);
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota);
function minimumStakeTime() external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to PeriFinance
function issuePynths(
address _issuer,
bytes32 _currencyKey,
uint _issueAmount
) external;
function issueMaxPynths(address _issuer) external;
function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external;
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external;
function fitToClaimable(address _from) external;
function exit(address _from) external;
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getPynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.pynths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.peri.finance/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.peri.finance/contracts/source/interfaces/iethercollateral
interface IEtherCollateral {
// Views
function totalIssuedPynths() external view returns (uint256);
function totalLoansCreated() external view returns (uint256);
function totalOpenLoanCount() external view returns (uint256);
// Mutative functions
function openLoan() external payable returns (uint256 loanID);
function closeLoan(uint256 loanID) external;
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external;
}
/**
* @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;
}
}
// Libraries
// https://docs.peri.finance/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @dev Round down the value with given number
*/
function roundDownDecimal(uint x, uint d) internal pure returns (uint) {
return x.div(10**d).mul(10**d);
}
/**
* @dev Round up the value with given number
*/
function roundUpDecimal(uint x, uint d) internal pure returns (uint) {
uint _decimal = 10**d;
if (x % _decimal > 0) {
x = x.add(10**d);
}
return x.div(_decimal).mul(_decimal);
}
}
// https://docs.peri.finance/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requirePynthActive(bytes32 currencyKey) external view;
function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getPynthExchangeSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getPynthSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendPynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.peri.finance/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to PeriFinance
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint pUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.peri.finance/contracts/source/interfaces/idepot
interface IDepot {
// Views
function fundsWallet() external view returns (address payable);
function maxEthPurchase() external view returns (uint);
function minimumDepositAmount() external view returns (uint);
function pynthsReceivedForEther(uint amount) external view returns (uint);
function totalSellableDeposits() external view returns (uint);
// Mutative functions
function depositPynths(uint amount) external;
function exchangeEtherForPynths() external payable returns (uint);
function exchangeEtherForPynthsAtRate(uint guaranteedRate) external payable returns (uint);
function withdrawMyDepositedPynths() external;
// Note: On mainnet no PERI has been deposited. The following functions are kept alive for testnet PERI faucets.
function exchangeEtherForPERI() external payable returns (uint);
function exchangeEtherForPERIAtRate(uint guaranteedRate, uint guaranteedPeriFinanceRate) external payable returns (uint);
function exchangePynthsForPERI(uint pynthAmount) external returns (uint);
function periFinanceReceivedForEther(uint amount) external view returns (uint);
function periFinanceReceivedForPynths(uint amount) external view returns (uint);
function withdrawPeriFinance(uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozenAtUpperLimit;
bool frozenAtLowerLimit;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
// Mutative functions
function freezeRate(bytes32 currencyKey) external;
}
// Inheritance
// Libraries
// Internal references
// https://docs.peri.finance/contracts/source/contracts/ethercollateral
contract EtherCollateral is Owned, Pausable, ReentrancyGuard, MixinResolver, IEtherCollateral {
using SafeMath for uint256;
using SafeDecimalMath for uint256;
// ========== CONSTANTS ==========
uint256 internal constant ONE_THOUSAND = 1e18 * 1000;
uint256 internal constant ONE_HUNDRED = 1e18 * 100;
uint256 internal constant SECONDS_IN_A_YEAR = 31536000; // Common Year
// Where fees are pooled in pUSD.
address internal constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
// ========== SETTER STATE VARIABLES ==========
// The ratio of Collateral to pynths issued
uint256 public collateralizationRatio = SafeDecimalMath.unit() * 125; // SCCP-27
// If updated, all outstanding loans will pay this interest rate in on closure of the loan. Default 5%
uint256 public interestRate = (5 * SafeDecimalMath.unit()) / 100;
uint256 public interestPerSecond = interestRate.div(SECONDS_IN_A_YEAR);
// Minting fee for issuing the pynths. Default 50 bips.
uint256 public issueFeeRate = (5 * SafeDecimalMath.unit()) / 1000;
// Maximum amount of pETH that can be issued by the EtherCollateral contract. Default 5000
uint256 public issueLimit = SafeDecimalMath.unit() * 5000;
// Minimum amount of ETH to create loan preventing griefing and gas consumption. Min 1ETH = 0.8 pETH
uint256 public minLoanSize = SafeDecimalMath.unit() * 1;
// Maximum number of loans an account can create
uint256 public accountLoanLimit = 50;
// If true then any wallet addres can close a loan not just the loan creator.
bool public loanLiquidationOpen = false;
// Time when remaining loans can be liquidated
uint256 public liquidationDeadline;
// ========== STATE VARIABLES ==========
// The total number of pynths issued by the collateral in this contract
uint256 public totalIssuedPynths;
// Total number of loans ever created
uint256 public totalLoansCreated;
// Total number of open loans
uint256 public totalOpenLoanCount;
// Pynth loan storage struct
struct PynthLoanStruct {
// Acccount that created the loan
address account;
// Amount (in collateral token ) that they deposited
uint256 collateralAmount;
// Amount (in pynths) that they issued to borrow
uint256 loanAmount;
// When the loan was created
uint256 timeCreated;
// ID for the loan
uint256 loanID;
// When the loan was paidback (closed)
uint256 timeClosed;
}
// Users Loans by address
mapping(address => PynthLoanStruct[]) public accountsPynthLoans;
// Account Open Loan Counter
mapping(address => uint256) public accountOpenLoanCounter;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_PYNTHPETH = "PynthpETH";
bytes32 private constant CONTRACT_PYNTHPUSD = "PynthpUSD";
bytes32 private constant CONTRACT_DEPOT = "Depot";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
// ========== CONSTRUCTOR ==========
constructor(address _owner, address _resolver) public Owned(_owner) Pausable() MixinResolver(_resolver) {
liquidationDeadline = now + 92 days; // Time before loans can be liquidated
}
// ========== SETTERS ==========
function setCollateralizationRatio(uint256 ratio) external onlyOwner {
require(ratio <= ONE_THOUSAND, "Too high");
require(ratio >= ONE_HUNDRED, "Too low");
collateralizationRatio = ratio;
emit CollateralizationRatioUpdated(ratio);
}
function setInterestRate(uint256 _interestRate) external onlyOwner {
require(_interestRate > SECONDS_IN_A_YEAR, "Interest rate cannot be less that the SECONDS_IN_A_YEAR");
require(_interestRate <= SafeDecimalMath.unit(), "Interest cannot be more than 100% APR");
interestRate = _interestRate;
interestPerSecond = _interestRate.div(SECONDS_IN_A_YEAR);
emit InterestRateUpdated(interestRate);
}
function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner {
issueFeeRate = _issueFeeRate;
emit IssueFeeRateUpdated(issueFeeRate);
}
function setIssueLimit(uint256 _issueLimit) external onlyOwner {
issueLimit = _issueLimit;
emit IssueLimitUpdated(issueLimit);
}
function setMinLoanSize(uint256 _minLoanSize) external onlyOwner {
minLoanSize = _minLoanSize;
emit MinLoanSizeUpdated(minLoanSize);
}
function setAccountLoanLimit(uint256 _loanLimit) external onlyOwner {
uint256 HARD_CAP = 1000;
require(_loanLimit < HARD_CAP, "Owner cannot set higher than HARD_CAP");
accountLoanLimit = _loanLimit;
emit AccountLoanLimitUpdated(accountLoanLimit);
}
function setLoanLiquidationOpen(bool _loanLiquidationOpen) external onlyOwner {
require(now > liquidationDeadline, "Before liquidation deadline");
loanLiquidationOpen = _loanLiquidationOpen;
emit LoanLiquidationOpenUpdated(loanLiquidationOpen);
}
// ========== PUBLIC VIEWS ==========
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](5);
addresses[0] = CONTRACT_SYSTEMSTATUS;
addresses[1] = CONTRACT_PYNTHPETH;
addresses[2] = CONTRACT_PYNTHPUSD;
addresses[3] = CONTRACT_DEPOT;
addresses[4] = CONTRACT_EXRATES;
}
function getContractInfo()
external
view
returns (
uint256 _collateralizationRatio,
uint256 _issuanceRatio,
uint256 _interestRate,
uint256 _interestPerSecond,
uint256 _issueFeeRate,
uint256 _issueLimit,
uint256 _minLoanSize,
uint256 _totalIssuedPynths,
uint256 _totalLoansCreated,
uint256 _totalOpenLoanCount,
uint256 _ethBalance,
uint256 _liquidationDeadline,
bool _loanLiquidationOpen
)
{
_collateralizationRatio = collateralizationRatio;
_issuanceRatio = issuanceRatio();
_interestRate = interestRate;
_interestPerSecond = interestPerSecond;
_issueFeeRate = issueFeeRate;
_issueLimit = issueLimit;
_minLoanSize = minLoanSize;
_totalIssuedPynths = totalIssuedPynths;
_totalLoansCreated = totalLoansCreated;
_totalOpenLoanCount = totalOpenLoanCount;
_ethBalance = address(this).balance;
_liquidationDeadline = liquidationDeadline;
_loanLiquidationOpen = loanLiquidationOpen;
}
// returns value of 100 / collateralizationRatio.
// e.g. 100/125 = 0.8
// or in wei 100000000000000000000/125000000000000000000 = 800000000000000000
function issuanceRatio() public view returns (uint256) {
// this Rounds so you get slightly more rather than slightly less
// 4999999999999999995000
return ONE_HUNDRED.divideDecimalRound(collateralizationRatio);
}
function loanAmountFromCollateral(uint256 collateralAmount) public view returns (uint256) {
return collateralAmount.multiplyDecimal(issuanceRatio());
}
function collateralAmountForLoan(uint256 loanAmount) external view returns (uint256) {
return loanAmount.multiplyDecimal(collateralizationRatio.divideDecimalRound(ONE_HUNDRED));
}
function currentInterestOnLoan(address _account, uint256 _loanID) external view returns (uint256) {
// Get the loan from storage
PynthLoanStruct memory pynthLoan = _getLoanFromStorage(_account, _loanID);
uint256 loanLifeSpan = _loanLifeSpan(pynthLoan);
return accruedInterestOnLoan(pynthLoan.loanAmount, loanLifeSpan);
}
function accruedInterestOnLoan(uint256 _loanAmount, uint256 _seconds) public view returns (uint256 interestAmount) {
// Simple interest calculated per second
// Interest = Principal * rate * time
interestAmount = _loanAmount.multiplyDecimalRound(interestPerSecond.mul(_seconds));
}
function calculateMintingFee(address _account, uint256 _loanID) external view returns (uint256) {
// Get the loan from storage
PynthLoanStruct memory pynthLoan = _getLoanFromStorage(_account, _loanID);
return _calculateMintingFee(pynthLoan);
}
function openLoanIDsByAccount(address _account) external view returns (uint256[] memory) {
PynthLoanStruct[] memory pynthLoans = accountsPynthLoans[_account];
uint256[] memory _openLoanIDs = new uint256[](pynthLoans.length);
uint256 _counter = 0;
for (uint256 i = 0; i < pynthLoans.length; i++) {
if (pynthLoans[i].timeClosed == 0) {
_openLoanIDs[_counter] = pynthLoans[i].loanID;
_counter++;
}
}
// Create the fixed size array to return
uint256[] memory _result = new uint256[](_counter);
// Copy loanIDs from dynamic array to fixed array
for (uint256 j = 0; j < _counter; j++) {
_result[j] = _openLoanIDs[j];
}
// Return an array with list of open Loan IDs
return _result;
}
function getLoan(address _account, uint256 _loanID)
external
view
returns (
address account,
uint256 collateralAmount,
uint256 loanAmount,
uint256 timeCreated,
uint256 loanID,
uint256 timeClosed,
uint256 interest,
uint256 totalFees
)
{
PynthLoanStruct memory pynthLoan = _getLoanFromStorage(_account, _loanID);
account = pynthLoan.account;
collateralAmount = pynthLoan.collateralAmount;
loanAmount = pynthLoan.loanAmount;
timeCreated = pynthLoan.timeCreated;
loanID = pynthLoan.loanID;
timeClosed = pynthLoan.timeClosed;
interest = accruedInterestOnLoan(pynthLoan.loanAmount, _loanLifeSpan(pynthLoan));
totalFees = interest.add(_calculateMintingFee(pynthLoan));
}
function loanLifeSpan(address _account, uint256 _loanID) external view returns (uint256 loanLifeSpanResult) {
PynthLoanStruct memory pynthLoan = _getLoanFromStorage(_account, _loanID);
loanLifeSpanResult = _loanLifeSpan(pynthLoan);
}
// ========== PUBLIC FUNCTIONS ==========
function openLoan() external payable notPaused nonReentrant pETHRateNotInvalid returns (uint256 loanID) {
systemStatus().requireIssuanceActive();
// Require ETH sent to be greater than minLoanSize
require(msg.value >= minLoanSize, "Not enough ETH to create this loan. Please see the minLoanSize");
// Require loanLiquidationOpen to be false or we are in liquidation phase
require(loanLiquidationOpen == false, "Loans are now being liquidated");
// Each account is limted to creating 50 (accountLoanLimit) loans
require(accountsPynthLoans[msg.sender].length < accountLoanLimit, "Each account is limted to 50 loans");
// Calculate issuance amount
uint256 loanAmount = loanAmountFromCollateral(msg.value);
// Require pETH to mint does not exceed cap
require(totalIssuedPynths.add(loanAmount) < issueLimit, "Loan Amount exceeds the supply cap.");
// Get a Loan ID
loanID = _incrementTotalLoansCounter();
// Create Loan storage object
PynthLoanStruct memory pynthLoan =
PynthLoanStruct({
account: msg.sender,
collateralAmount: msg.value,
loanAmount: loanAmount,
timeCreated: now,
loanID: loanID,
timeClosed: 0
});
// Record loan in mapping to account in an array of the accounts open loans
accountsPynthLoans[msg.sender].push(pynthLoan);
// Increment totalIssuedPynths
totalIssuedPynths = totalIssuedPynths.add(loanAmount);
// Issue the pynth
pynthpETH().issue(msg.sender, loanAmount);
// Tell the Dapps a loan was created
emit LoanCreated(msg.sender, loanID, loanAmount);
}
function closeLoan(uint256 loanID) external nonReentrant pETHRateNotInvalid {
_closeLoan(msg.sender, loanID);
}
// Liquidation of an open loan available for anyone
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external nonReentrant pETHRateNotInvalid {
require(loanLiquidationOpen, "Liquidation is not open");
// Close the creators loan and send collateral to the closer.
_closeLoan(_loanCreatorsAddress, _loanID);
// Tell the Dapps this loan was liquidated
emit LoanLiquidated(_loanCreatorsAddress, _loanID, msg.sender);
}
// ========== PRIVATE FUNCTIONS ==========
function _closeLoan(address account, uint256 loanID) private {
systemStatus().requireIssuanceActive();
// Get the loan from storage
PynthLoanStruct memory pynthLoan = _getLoanFromStorage(account, loanID);
require(pynthLoan.loanID > 0, "Loan does not exist");
require(pynthLoan.timeClosed == 0, "Loan already closed");
require(
IERC20(address(pynthpETH())).balanceOf(msg.sender) >= pynthLoan.loanAmount,
"You do not have the required Pynth balance to close this loan."
);
// Record loan as closed
_recordLoanClosure(pynthLoan);
// Decrement totalIssuedPynths
totalIssuedPynths = totalIssuedPynths.sub(pynthLoan.loanAmount);
// Calculate and deduct interest(5%) and minting fee(50 bips) in ETH
uint256 interestAmount = accruedInterestOnLoan(pynthLoan.loanAmount, _loanLifeSpan(pynthLoan));
uint256 mintingFee = _calculateMintingFee(pynthLoan);
uint256 totalFeeETH = interestAmount.add(mintingFee);
// Burn all Pynths issued for the loan
pynthpETH().burn(msg.sender, pynthLoan.loanAmount);
// Fee Distribution. Purchase pUSD with ETH from Depot
require(
IERC20(address(pynthpUSD())).balanceOf(address(depot())) >= depot().pynthsReceivedForEther(totalFeeETH),
"The pUSD Depot does not have enough pUSD to buy for fees"
);
depot().exchangeEtherForPynths.value(totalFeeETH)();
// Transfer the pUSD to distribute to PERI holders.
IERC20(address(pynthpUSD())).transfer(FEE_ADDRESS, IERC20(address(pynthpUSD())).balanceOf(address(this)));
// Send remainder ETH to caller
address(msg.sender).transfer(pynthLoan.collateralAmount.sub(totalFeeETH));
// Tell the Dapps
emit LoanClosed(account, loanID, totalFeeETH);
}
function _getLoanFromStorage(address account, uint256 loanID) private view returns (PynthLoanStruct memory) {
PynthLoanStruct[] memory pynthLoans = accountsPynthLoans[account];
for (uint256 i = 0; i < pynthLoans.length; i++) {
if (pynthLoans[i].loanID == loanID) {
return pynthLoans[i];
}
}
}
function _recordLoanClosure(PynthLoanStruct memory pynthLoan) private {
// Get storage pointer to the accounts array of loans
PynthLoanStruct[] storage pynthLoans = accountsPynthLoans[pynthLoan.account];
for (uint256 i = 0; i < pynthLoans.length; i++) {
if (pynthLoans[i].loanID == pynthLoan.loanID) {
// Record the time the loan was closed
pynthLoans[i].timeClosed = now;
}
}
// Reduce Total Open Loans Count
totalOpenLoanCount = totalOpenLoanCount.sub(1);
}
function _incrementTotalLoansCounter() private returns (uint256) {
// Increase the total Open loan count
totalOpenLoanCount = totalOpenLoanCount.add(1);
// Increase the total Loans Created count
totalLoansCreated = totalLoansCreated.add(1);
// Return total count to be used as a unique ID.
return totalLoansCreated;
}
function _calculateMintingFee(PynthLoanStruct memory pynthLoan) private view returns (uint256 mintingFee) {
mintingFee = pynthLoan.loanAmount.multiplyDecimalRound(issueFeeRate);
}
function _loanLifeSpan(PynthLoanStruct memory pynthLoan) private view returns (uint256 loanLifeSpanResult) {
// Get time loan is open for, and if closed from the timeClosed
bool loanClosed = pynthLoan.timeClosed > 0;
// Calculate loan life span in seconds as (Now - Loan creation time)
loanLifeSpanResult = loanClosed ? pynthLoan.timeClosed.sub(pynthLoan.timeCreated) : now.sub(pynthLoan.timeCreated);
}
/* ========== INTERNAL VIEWS ========== */
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function pynthpETH() internal view returns (IPynth) {
return IPynth(requireAndGetAddress(CONTRACT_PYNTHPETH));
}
function pynthpUSD() internal view returns (IPynth) {
return IPynth(requireAndGetAddress(CONTRACT_PYNTHPUSD));
}
function depot() internal view returns (IDepot) {
return IDepot(requireAndGetAddress(CONTRACT_DEPOT));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
/* ========== MODIFIERS ========== */
modifier pETHRateNotInvalid() {
require(!exchangeRates().rateIsInvalid("pETH"), "Blocked as pETH rate is invalid");
_;
}
// ========== EVENTS ==========
event CollateralizationRatioUpdated(uint256 ratio);
event InterestRateUpdated(uint256 interestRate);
event IssueFeeRateUpdated(uint256 issueFeeRate);
event IssueLimitUpdated(uint256 issueLimit);
event MinLoanSizeUpdated(uint256 minLoanSize);
event AccountLoanLimitUpdated(uint256 loanLimit);
event LoanLiquidationOpenUpdated(bool loanLiquidationOpen);
event LoanCreated(address indexed account, uint256 loanID, uint256 amount);
event LoanClosed(address indexed account, uint256 loanID, uint256 feesPaid);
event LoanLiquidated(address indexed account, uint256 loanID, address liquidator);
}
|
Acccount that created the loan Amount (in collateral token ) that they deposited Amount (in pynths) that they issued to borrow When the loan was created ID for the loan When the loan was paidback (closed)
|
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
function freezeRate(bytes32 currencyKey) external;
}
struct PynthLoanStruct {
address account;
uint256 collateralAmount;
uint256 loanAmount;
uint256 timeCreated;
uint256 loanID;
uint256 timeClosed;
}
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_PYNTHPETH = "PynthpETH";
bytes32 private constant CONTRACT_PYNTHPUSD = "PynthpUSD";
bytes32 private constant CONTRACT_DEPOT = "Depot";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
| 11,952,780 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IBearable.sol";
import "../tokens/TwoBitBears.sol";
/// @title Bearable base contract for accessing a deployed TwoBitBears ERC721
/// @dev You may inherit or deploy separately
contract Bearable is IBearable {
/// @dev Stores the address to the deployed TwoBitBears contract
TwoBitBears internal immutable _twoBitBears;
/// Constructs a new instance of the Bearable contract
/// @dev mainnet contract address is 0x8ed25B735A788f4f7129Db736FC64f3A241137B8
/// @param twoBitBears The address of the twoBitBears contract on the deployment blockchain
constructor(address twoBitBears) {
_twoBitBears = TwoBitBears(twoBitBears);
}
/// @inheritdoc IBearable
/// @dev Throws if the token ID is not valid. Requirements already handled by the .ownerOf() call
function ownsBear(address possibleOwner, uint256 tokenId) public view override returns (bool) {
return _twoBitBears.ownerOf(tokenId) == possibleOwner;
}
/// @inheritdoc IBearable
function totalBears() public view override returns (uint256) {
return _twoBitBears.totalSupply();
}
/// @inheritdoc IBearable
/// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call
function bearBottomColor(uint256 tokenId) public view override returns (ISVGTypes.Color memory color) {
IBearDetail.Detail memory details = _twoBitBears.details(tokenId);
color.red = details.bottomColor.red;
color.green = details.bottomColor.green;
color.blue = details.bottomColor.blue;
color.alpha = 0xFF;
}
/// @inheritdoc IBearable
/// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call
function bearMood(uint256 tokenId) public view override returns (BearMoodType) {
IBearDetail.Detail memory details = _twoBitBears.details(tokenId);
return BearMoodType(details.moodIndex);
}
/// @inheritdoc IBearable
/// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call
function bearSpecies(uint256 tokenId) public view override returns (BearSpeciesType) {
IBearDetail.Detail memory details = _twoBitBears.details(tokenId);
return BearSpeciesType(details.speciesIndex);
}
/// @inheritdoc IBearable
/// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call
function bearTopColor(uint256 tokenId) public view override returns (ISVGTypes.Color memory color) {
IBearDetail.Detail memory details = _twoBitBears.details(tokenId);
color.red = details.topColor.red;
color.green = details.topColor.green;
color.blue = details.topColor.blue;
color.alpha = 0xFF;
}
}
|
@inheritdoc IBearable Throws if the token ID is not valid. Requirements already handled by the .details() call
|
function bearMood(uint256 tokenId) public view override returns (BearMoodType) {
IBearDetail.Detail memory details = _twoBitBears.details(tokenId);
return BearMoodType(details.moodIndex);
}
| 13,007,017 |
pragma solidity ^0.5.16;
// Inheritance
import "./Owned.sol";
import "./SelfDestructible.sol";
import "./MixinResolver.sol";
import "./MixinSystemSettings.sol";
import "./interfaces/IExchangeRates.sol";
// Libraries
import "./SafeDecimalMath.sol";
// Internal references
// AggregatorInterface from Chainlink represents a decentralized pricing network for a single currency key
import "@chainlink/contracts-0.0.9/src/v0.5/interfaces/AggregatorInterface.sol";
// FlagsInterface from Chainlink addresses SIP-76
import "@chainlink/contracts-0.0.9/src/v0.5/interfaces/FlagsInterface.sol";
import "./interfaces/IExchanger.sol";
// https://docs.synthetix.io/contracts/source/contracts/ExchangeRates
contract ExchangeRates is Owned, SelfDestructible, MixinResolver, MixinSystemSettings, IExchangeRates {
using SafeMath for uint;
using SafeDecimalMath for uint;
// Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD'
mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates;
// The address of the oracle which pushes rate updates to this contract
address public oracle;
// Decentralized oracle networks that feed into pricing aggregators
mapping(bytes32 => AggregatorInterface) public aggregators;
// List of aggregator keys for convenient iteration
bytes32[] public aggregatorKeys;
// Do not allow the oracle to submit times any further forward into the future than this constant.
uint private constant ORACLE_FUTURE_LIMIT = 10 minutes;
int private constant AGGREGATOR_RATE_MULTIPLIER = 1e10;
mapping(bytes32 => InversePricing) public inversePricing;
bytes32[] public invertedKeys;
mapping(bytes32 => uint) public currentRoundForRate;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32[24] private addressesToCache = [CONTRACT_EXCHANGER];
//
// ========== CONSTRUCTOR ==========
constructor(
address _owner,
address _oracle,
address _resolver,
bytes32[] memory _currencyKeys,
uint[] memory _newRates
) public Owned(_owner) SelfDestructible() MixinResolver(_resolver, addressesToCache) MixinSystemSettings() {
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
// The sUSD rate is always 1 and is never stale.
_setRate("sUSD", SafeDecimalMath.unit(), now);
internalUpdateRates(_currencyKeys, _newRates, now);
}
/* ========== SETTERS ========== */
function setOracle(address _oracle) external onlyOwner {
oracle = _oracle;
emit OracleUpdated(oracle);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function updateRates(
bytes32[] calldata currencyKeys,
uint[] calldata newRates,
uint timeSent
) external onlyOracle returns (bool) {
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
function deleteRate(bytes32 currencyKey) external onlyOracle {
require(_getRate(currencyKey) > 0, "Rate is zero");
delete _rates[currencyKey][currentRoundForRate[currencyKey]];
currentRoundForRate[currencyKey]--;
emit RateDeleted(currencyKey);
}
function setInversePricing(
bytes32 currencyKey,
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool freezeAtUpperLimit,
bool freezeAtLowerLimit
) external onlyOwner {
// 0 < lowerLimit < entryPoint => 0 < entryPoint
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits");
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0) {
// then we are adding a new inverse pricing, so add this
invertedKeys.push(currencyKey);
}
inverse.entryPoint = entryPoint;
inverse.upperLimit = upperLimit;
inverse.lowerLimit = lowerLimit;
if (freezeAtUpperLimit || freezeAtLowerLimit) {
// When indicating to freeze, we need to know the rate to freeze it at - either upper or lower
// this is useful in situations where ExchangeRates is updated and there are existing inverted
// rates already frozen in the current contract that need persisting across the upgrade
inverse.frozenAtUpperLimit = freezeAtUpperLimit;
inverse.frozenAtLowerLimit = freezeAtLowerLimit;
emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, msg.sender);
} else {
// unfreeze if need be
inverse.frozenAtUpperLimit = false;
inverse.frozenAtLowerLimit = false;
}
// SIP-78
uint rate = _getRate(currencyKey);
if (rate > 0) {
exchanger().setLastExchangeRateForSynth(currencyKey, rate);
}
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
}
function removeInversePricing(bytes32 currencyKey) external onlyOwner {
require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists");
delete inversePricing[currencyKey];
// now remove inverted key from array
bool wasRemoved = removeFromArray(currencyKey, invertedKeys);
if (wasRemoved) {
emit InversePriceConfigured(currencyKey, 0, 0, 0);
}
}
function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner {
AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress);
// This check tries to make sure that a valid aggregator is being added.
// It checks if the aggregator is an existing smart contract that has implemented `latestTimestamp` function.
require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid");
if (address(aggregators[currencyKey]) == address(0)) {
aggregatorKeys.push(currencyKey);
}
aggregators[currencyKey] = aggregator;
emit AggregatorAdded(currencyKey, address(aggregator));
}
function removeAggregator(bytes32 currencyKey) external onlyOwner {
address aggregator = address(aggregators[currencyKey]);
require(aggregator != address(0), "No aggregator exists for key");
delete aggregators[currencyKey];
bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys);
if (wasRemoved) {
emit AggregatorRemoved(currencyKey, aggregator);
}
}
// SIP-75 Public keeper function to freeze a synth that is out of bounds
function freezeRate(bytes32 currencyKey) external {
InversePricing storage inverse = inversePricing[currencyKey];
require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate");
require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen");
uint rate = _getRate(currencyKey);
if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) {
inverse.frozenAtUpperLimit = (rate == inverse.upperLimit);
inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit);
emit InversePriceFrozen(currencyKey, rate, msg.sender);
} else {
revert("Rate within bounds");
}
}
/* ========== VIEWS ========== */
// SIP-75 View to determine if freezeRate can be called safely
function canFreezeRate(bytes32 currencyKey) external view returns (bool) {
InversePricing memory inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) {
return false;
} else {
uint rate = _getRate(currencyKey);
return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit));
}
}
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) {
uint count = 0;
currencies = new bytes32[](aggregatorKeys.length);
for (uint i = 0; i < aggregatorKeys.length; i++) {
bytes32 currencyKey = aggregatorKeys[i];
if (address(aggregators[currencyKey]) == aggregator) {
currencies[count++] = currencyKey;
}
}
}
function rateStalePeriod() external view returns (uint) {
return getRateStalePeriod();
}
function aggregatorWarningFlags() external view returns (address) {
return getAggregatorWarningFlags();
}
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time) {
RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey);
return (rateAndTime.rate, rateAndTime.time);
}
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint) {
uint roundId = startingRoundId;
uint nextTimestamp = 0;
while (true) {
(, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1);
// if there's no new round, then the previous roundId was the latest
if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) {
return roundId;
}
roundId++;
}
return roundId;
}
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) {
return _getCurrentRoundId(currencyKey);
}
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value) {
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
(uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc);
(uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest);
// Calculate the effective value by going from source -> USD -> destination
value = sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate);
}
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) {
return _getRateAndTimestampAtRound(currencyKey, roundId);
}
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256) {
return _getUpdatedTime(currencyKey);
}
function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) {
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]);
}
return lastUpdateTimes;
}
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value) {
(value, , ) = _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
)
{
return _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function rateForCurrency(bytes32 currencyKey) external view returns (uint) {
return _getRateAndUpdatedTime(currencyKey).rate;
}
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times)
{
rates = new uint[](numRounds);
times = new uint[](numRounds);
uint roundId = _getCurrentRoundId(currencyKey);
for (uint i = 0; i < numRounds; i++) {
(rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId);
if (roundId == 0) {
// if we hit the last round, then return what we have
return (rates, times);
} else {
roundId--;
}
}
}
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) {
uint[] memory _localRates = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
_localRates[i] = _getRate(currencyKeys[i]);
}
return _localRates;
}
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid)
{
rates = new uint[](currencyKeys.length);
uint256 _rateStalePeriod = getRateStalePeriod();
// fetch all flags at once
bool[] memory flagList = getFlagsForRates(currencyKeys);
for (uint i = 0; i < currencyKeys.length; i++) {
// do one lookup of the rate & time to minimize gas
RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]);
rates[i] = rateEntry.rate;
if (!anyRateInvalid && currencyKeys[i] != "sUSD") {
anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time);
}
}
}
function rateIsStale(bytes32 currencyKey) external view returns (bool) {
return _rateIsStale(currencyKey, getRateStalePeriod());
}
function rateIsFrozen(bytes32 currencyKey) external view returns (bool) {
return _rateIsFrozen(currencyKey);
}
function rateIsInvalid(bytes32 currencyKey) external view returns (bool) {
return
_rateIsStale(currencyKey, getRateStalePeriod()) ||
_rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()));
}
function rateIsFlagged(bytes32 currencyKey) external view returns (bool) {
return _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()));
}
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) {
// Loop through each key and check whether the data point is stale.
uint256 _rateStalePeriod = getRateStalePeriod();
bool[] memory flagList = getFlagsForRates(currencyKeys);
for (uint i = 0; i < currencyKeys.length; i++) {
if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) {
return true;
}
}
return false;
}
/* ========== INTERNAL FUNCTIONS ========== */
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER, "Missing Exchanger address"));
}
function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) {
FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags());
// fetch all flags at once
if (_flags != FlagsInterface(0)) {
address[] memory _aggregators = new address[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
_aggregators[i] = address(aggregators[currencyKeys[i]]);
}
flagList = _flags.getFlags(_aggregators);
} else {
flagList = new bool[](currencyKeys.length);
}
}
function _setRate(
bytes32 currencyKey,
uint256 rate,
uint256 time
) internal {
// Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators
currentRoundForRate[currencyKey]++;
_rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({
rate: uint216(rate),
time: uint40(time)
});
}
function internalUpdateRates(
bytes32[] memory currencyKeys,
uint[] memory newRates,
uint timeSent
) internal returns (bool) {
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
// Loop through each key and perform update.
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
// Should not set any rate to zero ever, as no asset will ever be
// truely worthless and still valid. In this scenario, we should
// delete the rate and remove it from the system.
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
// We should only update the rate if it's at least the same age as the last rate we've got.
if (timeSent < _getUpdatedTime(currencyKey)) {
continue;
}
// Ok, go ahead with the update.
_setRate(currencyKey, newRates[i], timeSent);
}
emit RatesUpdated(currencyKeys, newRates);
return true;
}
function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) {
for (uint i = 0; i < array.length; i++) {
if (array[i] == entry) {
delete array[i];
// Copy the last key into the place of the one we just deleted
// If there's only one key, this is array[0] = array[0].
// If we're deleting the last one, it's also a NOOP in the same way.
array[i] = array[array.length - 1];
// Decrease the size of the array by one.
array.length--;
return true;
}
}
return false;
}
function _rateOrInverted(bytes32 currencyKey, uint rate) internal view returns (uint newRate) {
// if an inverse mapping exists, adjust the price accordingly
InversePricing memory inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0 || rate == 0) {
// when no inverse is set or when given a 0 rate, return the rate, regardless of the inverse status
// (the latter is so when a new inverse is set but the underlying has no rate, it will return 0 as
// the rate, not the lowerLimit)
return rate;
}
newRate = rate;
// These cases ensures that if a price has been frozen, it stays frozen even if it returns to the bounds
if (inverse.frozenAtUpperLimit) {
newRate = inverse.upperLimit;
} else if (inverse.frozenAtLowerLimit) {
newRate = inverse.lowerLimit;
} else {
// this ensures any rate outside the limit will never be returned
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
// avoid negative numbers for unsigned ints, so set this to 0
// which by the requirement that lowerLimit be > 0 will
// cause this to freeze the price to the lowerLimit
newRate = 0;
} else {
newRate = doubleEntryPoint.sub(rate);
}
// now ensure the rate is between the bounds
if (newRate >= inverse.upperLimit) {
newRate = inverse.upperLimit;
} else if (newRate <= inverse.lowerLimit) {
newRate = inverse.lowerLimit;
}
}
}
function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) {
AggregatorInterface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorInterface(0)) {
return
RateAndUpdatedTime({
rate: uint216(
_rateOrInverted(currencyKey, uint(aggregator.latestAnswer() * AGGREGATOR_RATE_MULTIPLIER))
),
time: uint40(aggregator.latestTimestamp())
});
} else {
RateAndUpdatedTime memory entry = _rates[currencyKey][currentRoundForRate[currencyKey]];
return RateAndUpdatedTime({rate: uint216(_rateOrInverted(currencyKey, entry.rate)), time: entry.time});
}
}
function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) {
AggregatorInterface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorInterface(0)) {
return aggregator.latestRound();
} else {
return currentRoundForRate[currencyKey];
}
}
function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) {
AggregatorInterface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorInterface(0)) {
return (
_rateOrInverted(currencyKey, uint(aggregator.getAnswer(roundId) * AGGREGATOR_RATE_MULTIPLIER)),
aggregator.getTimestamp(roundId)
);
} else {
RateAndUpdatedTime memory update = _rates[currencyKey][roundId];
return (_rateOrInverted(currencyKey, update.rate), update.time);
}
}
function _getRate(bytes32 currencyKey) internal view returns (uint256) {
return _getRateAndUpdatedTime(currencyKey).rate;
}
function _getUpdatedTime(bytes32 currencyKey) internal view returns (uint256) {
return _getRateAndUpdatedTime(currencyKey).time;
}
function _effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
internal
view
returns (
uint value,
uint sourceRate,
uint destinationRate
)
{
sourceRate = _getRate(sourceCurrencyKey);
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) {
destinationRate = sourceRate;
value = sourceAmount;
} else {
// Calculate the effective value by going from source -> USD -> destination
destinationRate = _getRate(destinationCurrencyKey);
value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate);
}
}
function _rateIsStale(bytes32 currencyKey, uint _rateStalePeriod) internal view returns (bool) {
// sUSD is a special case and is never stale (check before an SLOAD of getRateAndUpdatedTime)
if (currencyKey == "sUSD") return false;
return _rateIsStaleWithTime(_rateStalePeriod, _getUpdatedTime(currencyKey));
}
function _rateIsStaleWithTime(uint _rateStalePeriod, uint _time) internal view returns (bool) {
return _time.add(_rateStalePeriod) < now;
}
function _rateIsFrozen(bytes32 currencyKey) internal view returns (bool) {
InversePricing memory inverse = inversePricing[currencyKey];
return inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit;
}
function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) {
// sUSD is a special case and is never invalid
if (currencyKey == "sUSD") return false;
address aggregator = address(aggregators[currencyKey]);
// when no aggregator or when the flags haven't been setup
if (aggregator == address(0) || flags == FlagsInterface(0)) {
return false;
}
return flags.getFlag(aggregator);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle {
require(msg.sender == oracle, "Only the oracle can perform this action");
_;
}
/* ========== EVENTS ========== */
event OracleUpdated(address newOracle);
event RatesUpdated(bytes32[] currencyKeys, uint[] newRates);
event RateDeleted(bytes32 currencyKey);
event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit);
event InversePriceFrozen(bytes32 currencyKey, uint rate, address initiator);
event AggregatorAdded(bytes32 currencyKey, address aggregator);
event AggregatorRemoved(bytes32 currencyKey, address aggregator);
}
|
0 < lowerLimit < entryPoint => 0 < entryPoint then we are adding a new inverse pricing, so add this When indicating to freeze, we need to know the rate to freeze it at - either upper or lower this is useful in situations where ExchangeRates is updated and there are existing inverted rates already frozen in the current contract that need persisting across the upgrade unfreeze if need be
|
function setInversePricing(
bytes32 currencyKey,
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool freezeAtUpperLimit,
bool freezeAtLowerLimit
) external onlyOwner {
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits");
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0) {
invertedKeys.push(currencyKey);
}
inverse.entryPoint = entryPoint;
inverse.upperLimit = upperLimit;
inverse.lowerLimit = lowerLimit;
if (freezeAtUpperLimit || freezeAtLowerLimit) {
inverse.frozenAtUpperLimit = freezeAtUpperLimit;
inverse.frozenAtLowerLimit = freezeAtLowerLimit;
emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, msg.sender);
inverse.frozenAtUpperLimit = false;
inverse.frozenAtLowerLimit = false;
}
if (rate > 0) {
exchanger().setLastExchangeRateForSynth(currencyKey, rate);
}
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
}
| 12,682,452 |
./full_match/1/0xA1E4ff1Fd20c49C958D0d6d9EA93adB220D2b675/sources/contracts/GracyStaking.sol
|
Methods for time ranges
|
function addTimeRange(
uint256 _amount,
uint256 _startTimestampDay,
uint256 _endTimestampDay
) external onlyOwner
{
uint256 length = pool.timeRanges.length;
if (length > 0) {
if (_startTimestampDay != pool.timeRanges[length-1].endTimestampDay) revert StartMustEqualLastEnd();
}
if (_endTimestampDay - _startTimestampDay < (SECONDS_PER_HOUR * 24)) revert TimeDiffMustBeMoreThan24Hours();
uint256 dayInSeconds = _endTimestampDay - _startTimestampDay;
uint256 rewardsPerHour = _amount * SECONDS_PER_HOUR / dayInSeconds;
TimeRange memory next = TimeRange(_startTimestampDay.toUint48(), _endTimestampDay.toUint48(), rewardsPerHour.toUint96());
pool.timeRanges.push(next);
}
| 2,922,040 |
/**
*Submitted for verification at Etherscan.io on 2021-09-04
*/
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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/cryptography/ECDSA.sol
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @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.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: contracts/ERC721Cells.sol
pragma solidity ^0.8.0;
/**
* @title ERC721Cells
* ERC721Cells - ERC721 Contract of The Cells Zone
*/
abstract contract ERC721Cells is ERC721Enumerable, Ownable {
using ECDSA for bytes32;
address signerAddress = 0x8E7c6DBdae809c79C9f8Aa0F9ACf05614b4EB548; // The Cells Zone Signer Address
uint256 private _currentTokenId = 386;
uint256 private _reservedTokenId = 0;
uint256 private MAX_RESERVED_ID = 386;
uint256 public mintedSupply = 0;
bool public lockingEnabled = false;
string public baseURI = "https://api.thecellszone.com/json/";
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
mapping (uint256 => string) public tokenIdToCellCode;
mapping (string => uint256) public cellCodeToTokenId;
mapping (address => mapping(uint => bool)) private lockNonces;
event CellAllocation(address indexed to, uint256 indexed fromTokenId, uint256 indexed toTokenId, uint256 data, bool isRandom);
event LockedCell(uint indexed tokenId, address owner, string cellCode, string tokenURI);
event PermanentURI(string _value, uint256 indexed _id);
constructor(
string memory _name,
string memory _symbol
) ERC721(_name, _symbol) {
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to, uint256 _numItemsAllocated, bool isRandom, uint256 data) public virtual onlyOwner {
uint256 newTokenId = _getNextTokenId();
for (uint256 i = 0; i < _numItemsAllocated; i++) {
_mint(_to, newTokenId + i);
}
_incrementTokenId(_numItemsAllocated);
emit CellAllocation(_to, newTokenId, newTokenId + _numItemsAllocated - 1, data, isRandom);
}
function mintCell(address _to, uint256 _numItemsAllocated, bool isRandom, uint256 data) internal virtual {
uint256 newTokenId = _getNextTokenId();
for (uint256 i = 0; i < _numItemsAllocated; i++) {
_mint(_to, newTokenId + i);
}
_incrementTokenId(_numItemsAllocated);
_incrementMintedSupply(_numItemsAllocated);
emit CellAllocation(_to, newTokenId, newTokenId + _numItemsAllocated - 1, data, isRandom);
}
function reserveTo(address _to, uint256 _numItemsAllocated, bool isRandom, uint256 data) public virtual onlyOwner {
uint256 newTokenId = _getNextReservedTokenId();
uint256 newCount = newTokenId + _numItemsAllocated;
require(newCount <= MAX_RESERVED_ID, "tokenId too high");
for (uint256 i = 0; i < _numItemsAllocated; i++) {
_mint(_to, newTokenId + i);
}
_incrementReservedTokenId(_numItemsAllocated);
emit CellAllocation(_to, newTokenId, newTokenId + _numItemsAllocated - 1, data, isRandom);
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId + 1;
}
function _getNextReservedTokenId() private view returns (uint256) {
return _reservedTokenId + 1;
}
function setSignerAddress(address _address) public virtual onlyOwner {
signerAddress = _address;
}
function toggleLocking() public virtual onlyOwner {
lockingEnabled = !lockingEnabled;
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId(uint256 num) private {
_currentTokenId += num;
}
function _incrementReservedTokenId(uint256 num) private {
_reservedTokenId += num;
}
function _incrementMintedSupply(uint256 num) private {
mintedSupply += num;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory newURI) public onlyOwner {
baseURI = newURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "invalid token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If exists, return ipfs URI
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked('ipfs://', _tokenURI));
}
// If not, return Cells API URI
return string(abi.encodePacked(base, Strings.toString(tokenId)));
}
/*
* Lock Cell forever
*/
function lockCell(
bytes memory signature,
uint256 tokenId,
uint256 nonce,
string memory cellCode,
string memory _tokenURI
) external {
require(lockingEnabled, "locking disabled");
require(ownerOf(tokenId) == msg.sender, "not your cell");
require(bytes(_tokenURIs[tokenId]).length == 0 || !lockNonces[msg.sender][nonce], "already locked");
bytes32 _hash = keccak256(abi.encode(msg.sender, tokenId, nonce, cellCode, _tokenURI));
bytes32 messageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash));
address signer = messageHash.recover(signature);
require(signer == signerAddress, "Signers don't match");
lockNonces[msg.sender][nonce] = true;
_setTokenURI(tokenId, _tokenURI);
_setCellCode(tokenId, cellCode);
emit LockedCell(tokenId, msg.sender, cellCode, _tokenURI);
emit PermanentURI(_tokenURI, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "invalid token");
_tokenURIs[tokenId] = _tokenURI;
}
function _setCellCode(uint256 tokenId, string memory _cellCode) internal virtual {
require(_exists(tokenId), "invalid token");
require(cellCodeToTokenId[_cellCode] == 0, "already set");
require(bytes(tokenIdToCellCode[tokenId]).length == 0, "already set");
cellCodeToTokenId[_cellCode] = tokenId;
tokenIdToCellCode[tokenId] = _cellCode;
}
}
// File: contracts/Cells.sol
pragma solidity ^0.8.0;
/**
______________ ______________ _________ ___________.____ .____ _________ __________________ _______ ___________
\__ ___/ | \_ _____/ \_ ___ \\_ _____/| | | | / _____/ \____ /\_____ \ \ \ \_ _____/
| | / ~ \ __)_ / \ \/ | __)_ | | | | \_____ \ / / / | \ / | \ | __)_
| | \ Y / \ \ \____| \| |___| |___ / \ / /_ / | \/ | \| \
|____| \___|_ /_______ / \______ /_______ /|_______ \_______ \/_______ / /_______ \\_______ /\____|__ /_______ /
\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/
**/
interface IERC20 {
function mint(address to, uint256 amount) external;
function transfer(address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
/**
* @title The Cells Zone
*
*/
contract Cells is ERC721Cells {
using ECDSA for bytes32;
bool public directMint = false;
bool public randomMint = true;
bool public packMint = false;
bool public signatureMint = true;
bool public bonusCoins = true;
uint256 public constant MAX_CELLS_PURCHASE = 25;
uint256 public constant MAX_CELLS = 29886;
uint256 public minMintable = 1;
uint256 public maxMintable = 29000;
uint256 public cellPrice = 0.025 ether;
uint256 public bonusCoinsAmount = 200;
IERC20 public celdaContract;
mapping (uint256 => uint256) public packPrices;
mapping (address => mapping(uint => bool)) private mintNonces;
constructor(address _erc20Address)
ERC721Cells("The Cells Zone", "CELLS")
{
celdaContract = IERC20(_erc20Address);
packPrices[0] = 0.02 ether;
packPrices[1] = 0.015 ether;
packPrices[2] = 0.01 ether;
}
function contractURI() public pure returns (string memory) {
return "https://api.thecellszone.com/contract/";
}
function toggleDirectMint() public onlyOwner {
directMint = !directMint;
}
function toggleRandomMint() public onlyOwner {
randomMint = !randomMint;
}
function togglePackMint() public onlyOwner {
packMint = !packMint;
}
function toggleSignatureMint() public onlyOwner {
signatureMint = !signatureMint;
}
function toggleBonusCoins() public onlyOwner {
bonusCoins = !bonusCoins;
}
function setBonusCoinsAmount(uint amount) public onlyOwner {
bonusCoinsAmount = amount;
}
function setCellPrice(uint256 newPrice) public onlyOwner {
cellPrice = newPrice;
}
function setPackPrice(uint packId, uint256 newPrice) public onlyOwner {
packPrices[packId] = newPrice;
}
function setMinMintable(uint quantity) public onlyOwner {
minMintable = quantity;
}
function setMaxMintable(uint quantity) public onlyOwner {
maxMintable = quantity;
}
function reserveCells(uint number, bool isRandom, uint256 data) public onlyOwner {
reserveTo(msg.sender, number, isRandom, data);
}
/**
* Mint Cells
*/
function mintCells(uint amount) public payable {
require(directMint, "Direct mint is not active");
require(amount >= minMintable, "Quantity too low");
require(amount <= MAX_CELLS_PURCHASE || mintedSupply + amount <= maxMintable || totalSupply() + amount <= MAX_CELLS, "Quantity too high");
require(cellPrice * amount <= msg.value, "Ether value sent is not correct");
mintCell(msg.sender, amount, randomMint, 0);
if (bonusCoins) {
sendBonusCoins(msg.sender, amount);
}
}
/**
* Batch Mint Cells
*/
function mintCellPack(uint amount) public payable {
require(packMint, "Pack mint is not active");
require(amount >= minMintable, "Quantity too low");
require(amount <= MAX_CELLS_PURCHASE || mintedSupply + amount <= maxMintable || totalSupply() + amount <= MAX_CELLS, "Quantity too high");
require(getPackPrice(amount) * amount <= msg.value, "Ether value sent is not correct");
mintCell(msg.sender, amount, randomMint, 0);
if (bonusCoins) {
sendBonusCoins(msg.sender, amount);
}
}
/**
* Authorized Mint
*/
function verifyAndMint(bytes memory signature, uint amount, uint nonce, uint mintPrice, uint data) public payable {
require(signatureMint, "Signature mint is not active");
require(amount >= minMintable, "Quantity too low");
require(amount <= MAX_CELLS_PURCHASE || mintedSupply + amount <= maxMintable || totalSupply() + amount <= MAX_CELLS, "Quantity too high");
require(!mintNonces[msg.sender][nonce], "Nonce already used");
uint price;
if (mintPrice == 1) {
price = getPackPrice(amount);
} else if (mintPrice == 2) {
price = cellPrice;
} else {
price = mintPrice;
}
require(price * amount <= msg.value, "Ether value sent is not correct");
bytes32 hash = keccak256(abi.encode(msg.sender, amount, nonce, mintPrice, data));
bytes32 messageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
address signer = messageHash.recover(signature);
require(signer == signerAddress, "Signers don't match");
mintNonces[msg.sender][nonce] = true;
mintCell(msg.sender, amount, randomMint, data);
if (bonusCoins) {
sendBonusCoins(msg.sender, amount);
}
}
function getPackPrice(uint256 _amount) internal view returns (uint256) {
uint256 price;
if (_amount < 3) {
price = cellPrice;
} else if (_amount < 10) {
price = packPrices[0];
} else if (_amount < 25) {
price = packPrices[1];
} else {
price = packPrices[2];
}
return price;
}
function sendBonusCoins(address _to, uint256 _amount) internal {
celdaContract.mint(_to, _amount * bonusCoinsAmount * 10**18);
}
function walletOfOwner(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
address payable sender = payable(msg.sender);
sender.transfer(balance);
}
function reclaimToken(IERC20 token) public onlyOwner {
require(address(token) != address(0));
uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, balance);
}
}
|
Mints a token to an address with a tokenURI. _to address of the future owner of the token/
|
function mintTo(address _to, uint256 _numItemsAllocated, bool isRandom, uint256 data) public virtual onlyOwner {
uint256 newTokenId = _getNextTokenId();
for (uint256 i = 0; i < _numItemsAllocated; i++) {
_mint(_to, newTokenId + i);
}
_incrementTokenId(_numItemsAllocated);
emit CellAllocation(_to, newTokenId, newTokenId + _numItemsAllocated - 1, data, isRandom);
}
| 7,895,250 |
./full_match/42/0x452d3623e3D87fEfB2534b516e0B259BA4993181/sources/PreachersCompFiLqdt.sol
|
Aave/ _asset is an address of an asset that we want to borrow using a flash loan, for example, ETH or DAI.
|
function flashloan(
address _asset,
uint256 _amount,
bytes memory _params) public onlyOwner()
{
ILendingPool lendingPool = ILendingPool( kLendingPool );
lendingPool.flashLoan(address(this), _asset, _amount, _params);
}
| 9,584,815 |
./full_match/80001/0xaC707F19F58D156FB70667BBa9FcDF2519a2fA78/sources/CornCoin.sol
|
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), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 849,640 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./../lib/uniswap/UniswapV2Library.sol";
import "./../lib/uniswap/UniswapV2OracleLibrary.sol";
import "./../lib/uniswap/FixedPoint.sol";
import "./../lib/math/MathUtils.sol";
import "./../external-interfaces/compound-finance/ICToken.sol";
import "./../external-interfaces/compound-finance/IComptroller.sol";
import "./../external-interfaces/compound-finance/IUniswapAnchoredOracle.sol";
import "./../external-interfaces/uniswap/IUniswapV2Router.sol";
import "./CompoundProvider.sol";
import "./../IController.sol";
import "./ICompoundCumulator.sol";
import "./../oracle/IYieldOracle.sol";
import "./../oracle/IYieldOraclelizable.sol";
contract CompoundController is IController, ICompoundCumulator, IYieldOraclelizable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address public constant UNISWAP_ROUTER_V2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uint256 public constant MAX_UINT256 = uint256(-1);
uint256 public constant DOUBLE_SCALE = 1e36;
uint256 public constant BLOCKS_PER_DAY = 5760; // 4 * 60 * 24 (assuming 4 blocks per minute)
uint256 public harvestedLast;
// last time we cumulated
uint256 public prevCumulationTime;
// exchnageRateStored last time we cumulated
uint256 public prevExchnageRateCurrent;
// cumulative supply rate += ((new underlying) / underlying)
uint256 public cumulativeSupplyRate;
// cumulative COMP distribution rate += ((new underlying) / underlying)
uint256 public cumulativeDistributionRate;
// compound.finance comptroller.compSupplyState right after the previous deposit/withdraw
IComptroller.CompMarketState public prevCompSupplyState;
uint256 public underlyingDecimals;
// uniswap path for COMP to underlying
address[] public uniswapPath;
// uniswap pairs for COMP to underlying
address[] public uniswapPairs;
// uniswap cumulative prices needed for COMP to underlying
uint256[] public uniswapPriceCumulatives;
// keys for uniswap cumulativePrice{0 | 1}
uint8[] public uniswapPriceKeys;
event Harvest(address indexed caller, uint256 compRewardTotal, uint256 compRewardSold, uint256 underlyingPoolShare, uint256 underlyingReward, uint256 harvestCost);
modifier onlyPool {
require(
msg.sender == pool,
"CC: only pool"
);
_;
}
constructor(
address pool_,
address smartYield_,
address bondModel_,
address[] memory uniswapPath_
)
IController()
{
pool = pool_;
smartYield = smartYield_;
underlyingDecimals = ERC20(ICToken(CompoundProvider(pool).cToken()).underlying()).decimals();
setBondModel(bondModel_);
setUniswapPath(uniswapPath_);
updateAllowances();
}
function updateAllowances()
public
{
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
IERC20 rewardToken = IERC20(comptroller.getCompAddress());
IERC20 uToken = IERC20(CompoundProvider(pool).uToken());
uint256 routerRewardAllowance = rewardToken.allowance(address(this), uniswapRouter());
rewardToken.safeIncreaseAllowance(uniswapRouter(), MAX_UINT256.sub(routerRewardAllowance));
uint256 poolUnderlyingAllowance = uToken.allowance(address(this), address(pool));
uToken.safeIncreaseAllowance(address(pool), MAX_UINT256.sub(poolUnderlyingAllowance));
}
// should start with rewardCToken and with uToken, and have intermediary hops if needed
// path[0] = address(rewardCToken);
// path[1] = address(wethToken);
// path[2] = address(uToken);
function setUniswapPath(address[] memory newUniswapPath_)
public virtual
onlyDao
{
require(
2 <= newUniswapPath_.length,
"CC: setUniswapPath length"
);
uniswapPath = newUniswapPath_;
address[] memory newUniswapPairs = new address[](newUniswapPath_.length - 1);
uint8[] memory newUniswapPriceKeys = new uint8[](newUniswapPath_.length - 1);
for (uint256 f = 0; f < newUniswapPath_.length - 1; f++) {
newUniswapPairs[f] = UniswapV2Library.pairFor(UNISWAP_FACTORY, newUniswapPath_[f], newUniswapPath_[f + 1]);
(address token0, ) = UniswapV2Library.sortTokens(newUniswapPath_[f], newUniswapPath_[f + 1]);
newUniswapPriceKeys[f] = token0 == newUniswapPath_[f] ? 0 : 1;
}
uniswapPairs = newUniswapPairs;
uniswapPriceKeys = newUniswapPriceKeys;
uniswapPriceCumulatives = uniswapPriceCumulativesNow();
}
function uniswapRouter()
public view virtual returns(address)
{
// mockable
return UNISWAP_ROUTER_V2;
}
// claims and sells COMP on uniswap, returns total received comp and caller reward
function harvest(uint256 maxCompAmount_)
public
returns (uint256 compGot, uint256 underlyingHarvestReward)
{
require(
harvestedLast < block.timestamp,
"PPC: harvest later"
);
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IERC20 uToken = IERC20(CompoundProvider(pool).uToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
IERC20 rewardToken = IERC20(comptroller.getCompAddress());
address caller = msg.sender;
// claim pool comp
address[] memory holders = new address[](1);
holders[0] = pool;
address[] memory markets = new address[](1);
markets[0] = address(cToken);
comptroller.claimComp(holders, markets, false, true);
// transfer all comp from pool to self
rewardToken.safeTransferFrom(pool, address(this), rewardToken.balanceOf(pool));
uint256 compRewardTotal = rewardToken.balanceOf(address(this)); // COMP
// only sell upmost maxCompAmount_, if maxCompAmount_ sell all
maxCompAmount_ = (maxCompAmount_ == 0) ? compRewardTotal : maxCompAmount_;
uint256 compRewardSold = MathUtils.min(maxCompAmount_, compRewardTotal);
require(
compRewardSold > 0,
"PPC: harvested nothing"
);
// pool share is (comp to underlying) - (harvest cost percent)
uint256 poolShare = MathUtils.fractionOf(
quoteSpotCompToUnderlying(compRewardSold),
EXP_SCALE.sub(HARVEST_COST)
);
// make sure we get at least the poolShare
IUniswapV2Router(uniswapRouter()).swapExactTokensForTokens(
compRewardSold,
poolShare,
uniswapPath,
address(this),
block.timestamp
);
uint256 underlyingGot = uToken.balanceOf(address(this));
require(
underlyingGot >= poolShare,
"PPC: harvest poolShare"
);
// deposit pool reward share with liquidity provider
CompoundProvider(pool)._takeUnderlying(address(this), poolShare);
CompoundProvider(pool)._depositProvider(poolShare, 0);
// pay caller
uint256 callerReward = uToken.balanceOf(address(this));
uToken.safeTransfer(caller, callerReward);
harvestedLast = block.timestamp;
emit Harvest(caller, compRewardTotal, compRewardSold, poolShare, callerReward, HARVEST_COST);
return (compRewardTotal, callerReward);
}
function _beforeCTokenBalanceChange()
external override
onlyPool
{ }
function _afterCTokenBalanceChange(uint256 prevCTokenBalance_)
external override
onlyPool
{
// at this point compound.finance state is updated since the pool did a deposit or withdrawl just before, so no need to ping
updateCumulativesInternal(prevCTokenBalance_, false);
IYieldOracle(oracle).update();
}
function providerRatePerDay()
public override virtual
returns (uint256)
{
return MathUtils.min(
MathUtils.min(BOND_MAX_RATE_PER_DAY, spotDailyRate()),
IYieldOracle(oracle).consult(1 days)
);
}
function cumulatives()
external override
returns (uint256)
{
uint256 timeElapsed = block.timestamp - prevCumulationTime;
// only cumulate once per block
if (0 == timeElapsed) {
return cumulativeSupplyRate.add(cumulativeDistributionRate);
}
uint256 cTokenBalance = CompoundProvider(pool).cTokenBalance();
updateCumulativesInternal(cTokenBalance, true);
return cumulativeSupplyRate.add(cumulativeDistributionRate);
}
function updateCumulativesInternal(uint256 prevCTokenBalance_, bool pingCompound_)
private
{
uint256 timeElapsed = block.timestamp - prevCumulationTime;
// only cumulate once per block
if (0 == timeElapsed) {
return;
}
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
uint256[] memory currentUniswapPriceCumulatives = uniswapPriceCumulativesNow();
if (pingCompound_) {
// echangeRateStored will be up to date below
cToken.accrueInterest();
// compSupplyState will be up to date below
comptroller.mintAllowed(address(cToken), address(this), 0);
}
uint256 exchangeRateStoredNow = cToken.exchangeRateStored();
(uint224 nowSupplyStateIndex, uint32 blk) = comptroller.compSupplyState(address(cToken));
if (prevExchnageRateCurrent > 0) {
// cumulate a new supplyRate delta: cumulativeSupplyRate += (cToken.exchangeRateCurrent() - prevExchnageRateCurrent) / prevExchnageRateCurrent
// cumulativeSupplyRate eventually overflows, but that's ok due to the way it's used in the oracle
cumulativeSupplyRate += exchangeRateStoredNow.sub(prevExchnageRateCurrent).mul(EXP_SCALE).div(prevExchnageRateCurrent);
if (prevCTokenBalance_ > 0) {
uint256 expectedComp = expectedDistributeSupplierComp(prevCTokenBalance_, nowSupplyStateIndex, prevCompSupplyState.index);
uint256 expectedCompInUnderlying = quoteCompToUnderlying(
expectedComp,
timeElapsed,
uniswapPriceCumulatives,
currentUniswapPriceCumulatives
);
uint256 poolShare = MathUtils.fractionOf(expectedCompInUnderlying, EXP_SCALE.sub(HARVEST_COST));
// cumulate a new distributionRate delta: cumulativeDistributionRate += (expectedDistributeSupplierComp in underlying - harvest cost) / prevUnderlyingBalance
// cumulativeDistributionRate eventually overflows, but that's ok due to the way it's used in the oracle
cumulativeDistributionRate += poolShare.mul(EXP_SCALE).div(cTokensToUnderlying(prevCTokenBalance_, prevExchnageRateCurrent));
}
}
prevCumulationTime = block.timestamp;
// uniswap cumulatives only change once per block
uniswapPriceCumulatives = currentUniswapPriceCumulatives;
// compSupplyState changes only once per block
prevCompSupplyState = IComptroller.CompMarketState(nowSupplyStateIndex, blk);
// exchangeRateStored can increase multiple times per block
prevExchnageRateCurrent = exchangeRateStoredNow;
}
// computes how much COMP tokens compound.finance will have given us after a mint/redeem/redeemUnderlying
// source: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol#L1145
function expectedDistributeSupplierComp(
uint256 cTokenBalance_, uint224 nowSupplyStateIndex_, uint224 prevSupplyStateIndex_
) public pure returns (uint256) {
uint256 supplyIndex = uint256(nowSupplyStateIndex_);
uint256 supplierIndex = uint256(prevSupplyStateIndex_);
uint256 deltaIndex = (supplyIndex).sub(supplierIndex); // a - b
return (cTokenBalance_).mul(deltaIndex).div(DOUBLE_SCALE); // a * b / doubleScale => uint
}
function cTokensToUnderlying(
uint256 cTokens_, uint256 exchangeRate_
) public pure returns (uint256) {
return cTokens_.mul(exchangeRate_).div(EXP_SCALE);
}
function uniswapPriceCumulativeNow(
address pair_, uint8 priceKey_
) public view returns (uint256) {
(uint256 price0, uint256 price1, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair_);
return 0 == priceKey_ ? price0 : price1;
}
function uniswapPriceCumulativesNow()
public view virtual returns (uint256[] memory)
{
uint256[] memory newUniswapPriceCumulatives = new uint256[](uniswapPairs.length);
for (uint256 f = 0; f < uniswapPairs.length; f++) {
newUniswapPriceCumulatives[f] = uniswapPriceCumulativeNow(uniswapPairs[f], uniswapPriceKeys[f]);
}
return newUniswapPriceCumulatives;
}
function quoteCompToUnderlying(
uint256 compIn_, uint256 timeElapsed_, uint256[] memory prevUniswapPriceCumulatives_, uint256[] memory nowUniswapPriceCumulatives_
) public pure returns (uint256) {
uint256 amountIn = compIn_;
for (uint256 f = 0; f < prevUniswapPriceCumulatives_.length; f++) {
amountIn = uniswapAmountOut(prevUniswapPriceCumulatives_[f], nowUniswapPriceCumulatives_[f], timeElapsed_, amountIn);
}
return amountIn;
}
function quoteSpotCompToUnderlying(
uint256 compIn_
) public view virtual returns (uint256) {
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(IComptroller(cToken.comptroller()).oracle());
uint256 underlyingOut = compIn_.mul(compOracle.price("COMP")).mul(10**12).div(compOracle.getUnderlyingPrice(address(cToken)));
return underlyingOut;
}
function uniswapAmountOut(
uint256 prevPriceCumulative_, uint256 nowPriceCumulative_, uint256 timeElapsed_, uint256 amountIn_
) public pure returns (uint256) {
// per: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol#L93
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((nowPriceCumulative_ - prevPriceCumulative_) / timeElapsed_)
);
return FixedPoint.decode144(FixedPoint.mul(priceAverage, amountIn_));
}
// compound spot supply rate per day
function spotDailySupplyRateProvider()
public view returns (uint256)
{
// supplyRatePerBlock() * BLOCKS_PER_DAY
return ICToken(CompoundProvider(pool).cToken()).supplyRatePerBlock().mul(BLOCKS_PER_DAY);
}
// compound spot distribution rate per day
function spotDailyDistributionRateProvider()
public view returns (uint256)
{
ICToken cToken = ICToken(CompoundProvider(pool).cToken());
IComptroller comptroller = IComptroller(cToken.comptroller());
IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(comptroller.oracle());
// compSpeeds(cToken) * price("COMP") * BLOCKS_PER_DAY
uint256 compDollarsPerDay = comptroller.compSpeeds(address(cToken)).mul(compOracle.price("COMP")).mul(BLOCKS_PER_DAY).mul(10**12);
// (totalBorrows() + getCash()) * getUnderlyingPrice(cToken)
uint256 totalSuppliedDollars = cToken.totalBorrows().add(cToken.getCash()).mul(compOracle.getUnderlyingPrice(address(cToken)));
// (compDollarsPerDay / totalSuppliedDollars)
return compDollarsPerDay.mul(EXP_SCALE).div(totalSuppliedDollars);
}
// smart yield spot daily rate includes: spot supply + spot distribution
function spotDailyRate()
public view returns (uint256)
{
uint256 expectedSpotDailyDistributionRate = MathUtils.fractionOf(spotDailyDistributionRateProvider(), EXP_SCALE.sub(HARVEST_COST));
// spotDailySupplyRateProvider() + (spotDailyDistributionRateProvider() - fraction lost to harvest)
return spotDailySupplyRateProvider().add(expectedSpotDailyDistributionRate);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import "@openzeppelin/contracts/math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import './FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
import './FullMath.sol';
import './Babylonian.sol';
import './BitMath.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 public constant RESOLUTION = 112;
uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
return uq144x112(z);
}
// multiply a UQ112x112 by an int and decode, returning an int
// reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
require(z < 2**255, 'FixedPoint::muli: overflow');
return y < 0 ? -int256(z) : int256(z);
}
// multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
// lossy
function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
if (self._x == 0 || other._x == 0) {
return uq112x112(0);
}
uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112
// partial products
uint224 upper = uint224(upper_self) * upper_other; // * 2^0
uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112
// so the bit shift does not overflow
require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
// so the cast does not overflow
require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
}
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
require(other._x > 0, 'FixedPoint::divuq: division by zero');
if (self._x == other._x) {
return uq112x112(uint224(Q112));
}
if (self._x <= uint144(-1)) {
uint256 value = (uint256(self._x) << RESOLUTION) / other._x;
require(value <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(value));
}
uint256 result = FullMath.mulDiv(Q112, self._x, other._x);
require(result <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(result));
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// can be lossy
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// take the reciprocal of a UQ112x112
// reverts on overflow
// lossy
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero');
require(self._x != 1, 'FixedPoint::reciprocal: overflow');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
library MathUtils {
using SafeMath for uint256;
uint256 public constant EXP_SCALE = 1e18;
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
function compound(
// in wei
uint256 principal,
// rate is * EXP_SCALE
uint256 ratePerPeriod,
uint16 periods
) internal pure returns (uint256) {
if (0 == ratePerPeriod) {
return principal;
}
while (periods > 0) {
// principal += principal * ratePerPeriod / EXP_SCALE;
principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE));
periods -= 1;
}
return principal;
}
function compound2(
uint256 principal,
uint256 ratePerPeriod,
uint16 periods
) internal pure returns (uint256) {
if (0 == ratePerPeriod) {
return principal;
}
while (periods > 0) {
if (periods % 2 == 1) {
//principal += principal * ratePerPeriod / EXP_SCALE;
principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE));
periods -= 1;
} else {
//ratePerPeriod = ((2 * ratePerPeriod * EXP_SCALE) + (ratePerPeriod * ratePerPeriod)) / EXP_SCALE;
ratePerPeriod = ((uint256(2).mul(ratePerPeriod).mul(EXP_SCALE)).add(ratePerPeriod.mul(ratePerPeriod))).div(EXP_SCALE);
periods /= 2;
}
}
return principal;
}
function linearGain(
uint256 principal,
uint256 ratePerPeriod,
uint16 periods
) internal pure returns (uint256) {
return principal.add(
fractionOf(principal, ratePerPeriod.mul(periods))
);
}
// computes a * f / EXP_SCALE
function fractionOf(uint256 a, uint256 f) internal pure returns (uint256) {
return a.mul(f).div(EXP_SCALE);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface ICToken {
function mint(uint mintAmount) external returns (uint256);
function redeemUnderlying(uint redeemAmount) external returns (uint256);
function accrueInterest() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrows() external view returns (uint256);
function getCash() external view returns (uint256);
function underlying() external view returns (address);
function comptroller() external view returns (address);
}
interface ICTokenErc20 {
function balanceOf(address to) external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface IComptroller {
struct CompMarketState {
uint224 index;
uint32 block;
}
function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) external;
function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256);
function getCompAddress() external view returns(address);
function compSupplyState(address cToken) external view returns (uint224, uint32);
function compSpeeds(address cToken) external view returns (uint256);
function oracle() external view returns (address);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface IUniswapAnchoredOracle {
function price(string memory symbol) external view returns (uint256);
function getUnderlyingPrice(address cToken) external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
interface IUniswapV2Router {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./../external-interfaces/compound-finance/ICToken.sol";
import "./../external-interfaces/compound-finance/IComptroller.sol";
import "./CompoundController.sol";
import "./ICompoundCumulator.sol";
import "./../IProvider.sol";
contract CompoundProvider is IProvider {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MAX_UINT256 = uint256(-1);
uint256 public constant EXP_SCALE = 1e18;
address public override smartYield;
address public override controller;
// fees colected in underlying
uint256 public override underlyingFees;
// underlying token (ie. DAI)
address public uToken; // IERC20
// claim token (ie. cDAI)
address public cToken;
// cToken.balanceOf(this) measuring only deposits by users (excludes direct cToken transfers to pool)
uint256 public cTokenBalance;
uint256 public exchangeRateCurrentCached;
uint256 public exchangeRateCurrentCachedAt;
bool public _setup;
event TransferFees(address indexed caller, address indexed feesOwner, uint256 fees);
modifier onlySmartYield {
require(
msg.sender == smartYield,
"PPC: only smartYield"
);
_;
}
modifier onlyController {
require(
msg.sender == controller,
"PPC: only controller"
);
_;
}
modifier onlySmartYieldOrController {
require(
msg.sender == smartYield || msg.sender == controller,
"PPC: only smartYield/controller"
);
_;
}
modifier onlyControllerOrDao {
require(
msg.sender == controller || msg.sender == CompoundController(controller).dao(),
"PPC: only controller/DAO"
);
_;
}
constructor(address cToken_)
{
cToken = cToken_;
uToken = ICToken(cToken_).underlying();
}
function setup(
address smartYield_,
address controller_
)
external
{
require(
false == _setup,
"PPC: already setup"
);
smartYield = smartYield_;
controller = controller_;
_enterMarket();
updateAllowances();
_setup = true;
}
function setController(address newController_)
external override
onlyControllerOrDao
{
// remove allowance on old controller
IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress());
rewardToken.safeApprove(controller, 0);
controller = newController_;
// give allowance to new controler
updateAllowances();
}
function updateAllowances()
public
{
IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress());
uint256 controllerRewardAllowance = rewardToken.allowance(address(this), controller);
rewardToken.safeIncreaseAllowance(controller, MAX_UINT256.sub(controllerRewardAllowance));
}
// externals
// take underlyingAmount_ from from_
function _takeUnderlying(address from_, uint256 underlyingAmount_)
external override
onlySmartYieldOrController
{
uint256 balanceBefore = IERC20(uToken).balanceOf(address(this));
IERC20(uToken).safeTransferFrom(from_, address(this), underlyingAmount_);
uint256 balanceAfter = IERC20(uToken).balanceOf(address(this));
require(
0 == (balanceAfter - balanceBefore - underlyingAmount_),
"PPC: _takeUnderlying amount"
);
}
// transfer away underlyingAmount_ to to_
function _sendUnderlying(address to_, uint256 underlyingAmount_)
external override
onlySmartYield
{
uint256 balanceBefore = IERC20(uToken).balanceOf(to_);
IERC20(uToken).safeTransfer(to_, underlyingAmount_);
uint256 balanceAfter = IERC20(uToken).balanceOf(to_);
require(
0 == (balanceAfter - balanceBefore - underlyingAmount_),
"PPC: _sendUnderlying amount"
);
}
// deposit underlyingAmount_ with the liquidity provider, callable by smartYield or controller
function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_)
external override
onlySmartYieldOrController
{
_depositProviderInternal(underlyingAmount_, takeFees_);
}
// deposit underlyingAmount_ with the liquidity provider, store resulting cToken balance in cTokenBalance
function _depositProviderInternal(uint256 underlyingAmount_, uint256 takeFees_)
internal
{
// underlyingFees += takeFees_
underlyingFees = underlyingFees.add(takeFees_);
ICompoundCumulator(controller)._beforeCTokenBalanceChange();
IERC20(uToken).safeApprove(address(cToken), underlyingAmount_);
uint256 err = ICToken(cToken).mint(underlyingAmount_);
require(0 == err, "PPC: _depositProvider mint");
ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance);
// cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls
cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this));
}
// withdraw underlyingAmount_ from the liquidity provider, callable by smartYield
function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_)
external override
onlySmartYield
{
_withdrawProviderInternal(underlyingAmount_, takeFees_);
}
// withdraw underlyingAmount_ from the liquidity provider, store resulting cToken balance in cTokenBalance
function _withdrawProviderInternal(uint256 underlyingAmount_, uint256 takeFees_)
internal
{
// underlyingFees += takeFees_;
underlyingFees = underlyingFees.add(takeFees_);
ICompoundCumulator(controller)._beforeCTokenBalanceChange();
uint256 err = ICToken(cToken).redeemUnderlying(underlyingAmount_);
require(0 == err, "PPC: _withdrawProvider redeemUnderlying");
ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance);
// cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls
cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this));
}
function transferFees()
external
override
{
_withdrawProviderInternal(underlyingFees, 0);
underlyingFees = 0;
uint256 fees = IERC20(uToken).balanceOf(address(this));
address to = CompoundController(controller).feesOwner();
IERC20(uToken).safeTransfer(to, fees);
emit TransferFees(msg.sender, to, fees);
}
// current total underlying balance, as measured by pool, without fees
function underlyingBalance()
external virtual override
returns (uint256)
{
// https://compound.finance/docs#protocol-math
// (total balance in underlying) - underlyingFees
// cTokenBalance * exchangeRateCurrent() / EXP_SCALE - underlyingFees;
return cTokenBalance.mul(exchangeRateCurrent()).div(EXP_SCALE).sub(underlyingFees);
}
// /externals
// public
// get exchangeRateCurrent from compound and cache it for the current block
function exchangeRateCurrent()
public virtual
returns (uint256)
{
// only once per block
if (block.timestamp > exchangeRateCurrentCachedAt) {
exchangeRateCurrentCachedAt = block.timestamp;
exchangeRateCurrentCached = ICToken(cToken).exchangeRateCurrent();
}
return exchangeRateCurrentCached;
}
// /public
// internals
// call comptroller.enterMarkets()
// needs to be called only once BUT before any interactions with the provider
function _enterMarket()
internal
{
address[] memory markets = new address[](1);
markets[0] = cToken;
uint256[] memory err = IComptroller(ICToken(cToken).comptroller()).enterMarkets(markets);
require(err[0] == 0, "PPC: _enterMarket");
}
// /internals
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./Governed.sol";
import "./IProvider.sol";
import "./ISmartYield.sol";
abstract contract IController is Governed {
uint256 public constant EXP_SCALE = 1e18;
address public pool; // compound provider pool
address public smartYield; // smartYield
address public oracle; // IYieldOracle
address public bondModel; // IBondModel
address public feesOwner; // fees are sent here
// max accepted cost of harvest when converting COMP -> underlying,
// if harvest gets less than (COMP to underlying at spot price) - HARVEST_COST%, it will revert.
// if it gets more, the difference goes to the harvest caller
uint256 public HARVEST_COST = 40 * 1e15; // 4%
// fee for buying jTokens
uint256 public FEE_BUY_JUNIOR_TOKEN = 3 * 1e15; // 0.3%
// fee for redeeming a sBond
uint256 public FEE_REDEEM_SENIOR_BOND = 100 * 1e15; // 10%
// max rate per day for sBonds
uint256 public BOND_MAX_RATE_PER_DAY = 719065000000000; // APY 30% / year
// max duration of a purchased sBond
uint16 public BOND_LIFE_MAX = 90; // in days
bool public PAUSED_BUY_JUNIOR_TOKEN = false;
bool public PAUSED_BUY_SENIOR_BOND = false;
function setHarvestCost(uint256 newValue_)
public
onlyDao
{
require(
HARVEST_COST < EXP_SCALE,
"IController: HARVEST_COST too large"
);
HARVEST_COST = newValue_;
}
function setBondMaxRatePerDay(uint256 newVal_)
public
onlyDao
{
BOND_MAX_RATE_PER_DAY = newVal_;
}
function setBondLifeMax(uint16 newVal_)
public
onlyDao
{
BOND_LIFE_MAX = newVal_;
}
function setFeeBuyJuniorToken(uint256 newVal_)
public
onlyDao
{
FEE_BUY_JUNIOR_TOKEN = newVal_;
}
function setFeeRedeemSeniorBond(uint256 newVal_)
public
onlyDao
{
FEE_REDEEM_SENIOR_BOND = newVal_;
}
function setPaused(bool buyJToken_, bool buySBond_)
public
onlyDaoOrGuardian
{
PAUSED_BUY_JUNIOR_TOKEN = buyJToken_;
PAUSED_BUY_SENIOR_BOND = buySBond_;
}
function setOracle(address newVal_)
public
onlyDao
{
oracle = newVal_;
}
function setBondModel(address newVal_)
public
onlyDao
{
bondModel = newVal_;
}
function setFeesOwner(address newVal_)
public
onlyDao
{
feesOwner = newVal_;
}
function yieldControllTo(address newController_)
public
onlyDao
{
IProvider(pool).setController(newController_);
ISmartYield(smartYield).setController(newController_);
}
function providerRatePerDay() external virtual returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface ICompoundCumulator {
function _beforeCTokenBalanceChange() external;
function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOracle {
function update() external;
function consult(uint256 forInterval) external returns (uint256 amountOut);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOraclelizable {
// accumulates/updates internal state and returns cumulatives
// oracle should call this when updating
function cumulatives()
external
returns(uint256 cumulativeYield);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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: 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);
}
}
// 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.5.0;
library BitMath {
// returns the 0 indexed position of the most significant bit of the input x
// s.t. x >= 2**msb and x < 2**(msb+1)
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
// returns the 0 indexed position of the least significant bit of the input x
// s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0)
// i.e. the bit at the index is set and the mask of all lower bits is 0
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::leastSignificantBit: zero');
r = 255;
if (x & uint128(-1) > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IProvider {
function smartYield() external view returns (address);
function controller() external view returns (address);
function underlyingFees() external view returns (uint256);
// deposit underlyingAmount_ into provider, add takeFees_ to fees
function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external;
// withdraw underlyingAmount_ from provider, add takeFees_ to fees
function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external;
function _takeUnderlying(address from_, uint256 amount_) external;
function _sendUnderlying(address to_, uint256 amount_) external;
function transferFees() external;
// current total underlying balance as measured by the provider pool, without fees
function underlyingBalance() external returns (uint256);
function setController(address newController_) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
abstract contract Governed {
address public dao;
address public guardian;
modifier onlyDao {
require(
dao == msg.sender,
"GOV: not dao"
);
_;
}
modifier onlyDaoOrGuardian {
require(
msg.sender == dao || msg.sender == guardian,
"GOV: not dao/guardian"
);
_;
}
constructor()
{
dao = msg.sender;
guardian = msg.sender;
}
function setDao(address dao_)
external
onlyDao
{
dao = dao_;
}
function setGuardian(address guardian_)
external
onlyDao
{
guardian = guardian_;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface ISmartYield {
// a senior BOND (metadata for NFT)
struct SeniorBond {
// amount seniors put in
uint256 principal;
// amount yielded at the end. total = principal + gain
uint256 gain;
// bond was issued at timestamp
uint256 issuedAt;
// bond matures at timestamp
uint256 maturesAt;
// was it liquidated yet
bool liquidated;
}
// a junior BOND (metadata for NFT)
struct JuniorBond {
// amount of tokens (jTokens) junior put in
uint256 tokens;
// bond matures at timestamp
uint256 maturesAt;
}
// a checkpoint for all JuniorBonds with same maturity date JuniorBond.maturesAt
struct JuniorBondsAt {
// sum of JuniorBond.tokens for JuniorBonds with the same JuniorBond.maturesAt
uint256 tokens;
// price at which JuniorBonds will be paid. Initially 0 -> unliquidated (price is in the future or not yet liquidated)
uint256 price;
}
function controller() external view returns (address);
function buyBond(uint256 principalAmount_, uint256 minGain_, uint256 deadline_, uint16 forDays_) external returns (uint256);
function redeemBond(uint256 bondId_) external;
function unaccountBonds(uint256[] memory bondIds_) external;
function buyTokens(uint256 underlyingAmount_, uint256 minTokens_, uint256 deadline_) external;
/**
* sell all tokens instantly
*/
function sellTokens(uint256 tokens_, uint256 minUnderlying_, uint256 deadline_) external;
function buyJuniorBond(uint256 tokenAmount_, uint256 maxMaturesAt_, uint256 deadline_) external;
function redeemJuniorBond(uint256 jBondId_) external;
function liquidateJuniorBonds(uint256 upUntilTimestamp_) external;
/**
* token purchase price
*/
function price() external returns (uint256);
function abondPaid() external view returns (uint256);
function abondDebt() external view returns (uint256);
function abondGain() external view returns (uint256);
/**
* @notice current total underlying balance, without accruing interest
*/
function underlyingTotal() external returns (uint256);
/**
* @notice current underlying loanable, without accruing interest
*/
function underlyingLoanable() external returns (uint256);
function underlyingJuniors() external returns (uint256);
function bondGain(uint256 principalAmount_, uint16 forDays_) external returns (uint256);
function maxBondDailyRate() external returns (uint256);
function setController(address newController_) external;
}
|
deposit underlyingAmount_ with the liquidity provider, store resulting cToken balance in cTokenBalance underlyingFees += takeFees_ cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls
|
function _depositProviderInternal(uint256 underlyingAmount_, uint256 takeFees_)
internal
{
underlyingFees = underlyingFees.add(takeFees_);
ICompoundCumulator(controller)._beforeCTokenBalanceChange();
IERC20(uToken).safeApprove(address(cToken), underlyingAmount_);
uint256 err = ICToken(cToken).mint(underlyingAmount_);
require(0 == err, "PPC: _depositProvider mint");
ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance);
cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this));
}
| 5,823,905 |
pragma solidity >=0.7.6;
contract MetaProxyFactory {
/// @dev Creates a new proxy for `targetContract` with metadata from calldata.
/// Copies everything from calldata except the first 4 bytes.
/// @return addr A non-zero address if successful.
function _metaProxyFromCalldata (address targetContract) internal returns (address addr) {
// the following assembly code (init code + contract code) constructs a metaproxy.
assembly {
// load free memory pointer as per solidity convention
let start := mload(64)
// copy
let ptr := start
// deploy code (11 bytes) + first part of the proxy (21 bytes)
mstore(ptr, 0x600b380380600b3d393df3363d3d373d3d3d3d60368038038091363936013d73)
ptr := add(ptr, 32)
// store the address of the contract to be called
mstore(ptr, shl(96, targetContract))
// 20 bytes
ptr := add(ptr, 20)
// the remaining proxy code...
mstore(ptr, 0x5af43d3d93803e603457fd5bf300000000000000000000000000000000000000)
// ...13 bytes
ptr := add(ptr, 13)
// now calculdate the size and copy the metadata
// - 4 bytes function signature
let size := sub(calldatasize(), 4)
// copy
calldatacopy(ptr, 4, size)
ptr := add(ptr, size)
// store the size of the metadata at the end of the bytecode
mstore(ptr, size)
ptr := add(ptr, 32)
// The size is deploy code + contract code + calldatasize - 4 + 32.
addr := create(0, start, sub(ptr, start))
}
}
/// @dev Creates a proxy for `targetContract` with metadata from `metadata`.
/// @return A non-zero address if successful.
function _metaProxyFromBytes (address targetContract, bytes memory metadata) internal returns (address) {
uint256 ptr;
assembly {
ptr := add(metadata, 32)
}
return _metaProxyFromMemory(targetContract, ptr, metadata.length);
}
/// @dev Creates a new proxy for `targetContract` with metadata from memory starting at `offset` and `length` bytes.
/// @return addr A non-zero address if successful.
function _metaProxyFromMemory (address targetContract, uint256 offset, uint256 length) internal returns (address addr) {
// the following assembly code (init code + contract code) constructs a metaproxy.
assembly {
// load free memory pointer as per solidity convention
let start := mload(64)
// keep a copy
let ptr := start
// deploy code (11 bytes) + first part of the proxy (21 bytes)
mstore(ptr, 0x600b380380600b3d393df3363d3d373d3d3d3d60368038038091363936013d73)
ptr := add(ptr, 32)
// store the address of the contract to be called
mstore(ptr, shl(96, targetContract))
// 20 bytes
ptr := add(ptr, 20)
// the remaining proxy code...
mstore(ptr, 0x5af43d3d93803e603457fd5bf300000000000000000000000000000000000000)
// ...13 bytes
ptr := add(ptr, 13)
// copy the metadata
{
for { let i := 0 } lt(i, length) { i := add(i, 32) } {
mstore(add(ptr, i), mload(add(offset, i)))
}
}
ptr := add(ptr, length)
// store the siz of the metadata at the end of the bytecode
mstore(ptr, length)
ptr := add(ptr, 32)
// The size is deploy code + contract code + calldatasize - 4 + 32.
addr := create(0, start, sub(ptr, start))
}
}
}
|
Creates a new proxy for `targetContract` with metadata from memory starting at `offset` and `length` bytes. return addr A non-zero address if successful. the following assembly code (init code + contract code) constructs a metaproxy. load free memory pointer as per solidity convention keep a copy deploy code (11 bytes) + first part of the proxy (21 bytes) store the address of the contract to be called 20 bytes the remaining proxy code... ...13 bytes copy the metadata
|
function _metaProxyFromMemory (address targetContract, uint256 offset, uint256 length) internal returns (address addr) {
assembly {
let start := mload(64)
let ptr := start
mstore(ptr, 0x600b380380600b3d393df3363d3d373d3d3d3d60368038038091363936013d73)
ptr := add(ptr, 32)
mstore(ptr, shl(96, targetContract))
ptr := add(ptr, 20)
mstore(ptr, 0x5af43d3d93803e603457fd5bf300000000000000000000000000000000000000)
ptr := add(ptr, 13)
{
mstore(add(ptr, i), mload(add(offset, i)))
}
}
ptr := add(ptr, length)
ptr := add(ptr, 32)
}
| 1,078,423 |
./full_match/4/0x35067174E17f3eD9B62F8eF60508F31BCDcF64dF/sources/src/contracts/reader/GPv2TradeSimulator.sol
|
Executes interactions.
|
function executeInteractions(GPv2Interaction.Data[] calldata interactions)
private
{
for (uint256 i; i < interactions.length; i++) {
GPv2Interaction.execute(interactions[i]);
}
}
| 12,510,288 |
// Copyright © 2021 Treum.io, a ConsenSys AG company. All rights reserved.
// BY USING THIS SMART CONTRACT, INCLUDING TO BUY, SELL, CREATE, BURN OR USE TOKENS, YOU AGREE TO EULERBEATS’ TERMS OF SERVICE, AVAILABLE HERE: HTTPS://EULERBEATS.COM/TERMS-OF-SERVICE AND IN THE TRANSACTION DATA OF 0x56ff8befa16e6720f9cf54146c9c5e3be9a1258fd910fe55c287f19ad80b8bc1
// SHA256 of artwork generation script: 65301d8425ba637bdb6328a17dbe7440bf1c7f5032879aad4c00bfa09bddf93f
pragma solidity =0.7.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./RoyaltyDistributor.sol";
// EulerBeats are generative visual & audio art pieces. The recipe and instructions to re-create the visualization and music reside on Ethereum blockchain.
//
// To recreate your art, you will need to retrieve the script
//
// STEPS TO RETRIEVE THE SCRIPTS:
// - The artwork re-generation script is written in JavaScript, split into pieces, and stored on chain.
// - Query the contract for the scriptCount - this is the number of pieces of the re-genereation script. You will need all of them.
// - Run the getScriptAtIndex method in the EulerBeats smart contract starting with parameter 0, this is will return a transaction hash
// - The "Input Data" field of this transaction contains the first segment of the script. Convert this into UTF-8 format
// - Repeat these last two steps, incrementing the parameter in the getScriptAtIndex method until the number of script segments matches the scrtipCount
contract EulerBeatsV2 is Ownable, ERC1155, ReentrancyGuard, RoyaltyDistributor {
using SafeMath for uint256;
using Strings for uint256;
using Address for address payable;
/***********************************|
| Variables and Events |
|__________________________________*/
// For Mint, mintPrint, and burnPrint: locks the prices
bool public mintPrintEnabled = false;
bool public burnPrintEnabled = false;
bool public mintEnabled = false;
bool private _contractMintPrintEnabled = false;
// For metadata (scripts), when locked it is irreversible
bool private _locked = false;
// Number of script sections stored
uint256 public scriptCount = 0;
// The scripts that can be used to render the NFT (audio and visual)
mapping (uint256 => string) public scripts;
// The bit flag to distinguish prints
uint256 constant public PRINTS_FLAG_BIT = 1;
// Supply restriction on prints
uint256 constant public MAX_PRINT_SUPPLY = 160;
// Supply restriction on seeds/original NFTs
uint256 constant public MAX_SEEDS_SUPPLY = 27;
// Total supply of prints and original NFTs
mapping(uint256 => uint256) public totalSupply;
// Total number of original NFTs minted
uint256 public originalsMinted = 0;
// Funds reserved for burns
uint256 public reserve = 0;
// Contract name
string public name;
// Contract symbol
string public symbol;
// Constants for bonding curve pricing
uint256 constant public A = 12;
uint256 constant public B = 140;
uint256 constant public C = 100;
uint256 constant public SIG_DIGITS = 3;
// Base uri for overriding ERC1155's uri getter
string internal _baseURI;
/**
* @dev Emitted when an original NFT with a new seed is minted
*/
event MintOriginal(address indexed to, uint256 seed, uint256 indexed originalsMinted);
/**
* @dev Emitted when an print is minted
*/
event PrintMinted(
address indexed to,
uint256 id,
uint256 indexed seed,
uint256 pricePaid,
uint256 nextPrintPrice,
uint256 nextBurnPrice,
uint256 printsSupply,
uint256 royaltyPaid,
uint256 reserve,
address indexed royaltyRecipient
);
/**
* @dev Emitted when an print is burned
*/
event PrintBurned(
address indexed to,
uint256 id,
uint256 indexed seed,
uint256 priceReceived,
uint256 nextPrintPrice,
uint256 nextBurnPrice,
uint256 printsSupply,
uint256 reserve
);
constructor(string memory _name, string memory _symbol, string memory _uri) ERC1155("") {
name = _name;
symbol = _symbol;
_baseURI = _uri;
}
/***********************************|
| Modifiers |
|__________________________________*/
modifier onlyWhenMintEnabled() {
require(mintEnabled, "Minting originals is disabled");
_;
}
modifier onlyWhenMintPrintEnabled() {
require(mintPrintEnabled, "Minting prints is disabled");
_;
}
modifier onlyWhenBurnPrintEnabled() {
require(burnPrintEnabled, "Burning prints is disabled");
_;
}
modifier onlyUnlocked() {
require(!_locked, "Contract is locked");
_;
}
/***********************************|
| User Interactions |
|__________________________________*/
/**
* @dev Function to mint tokens. Not payable for V2, restricted to owner
*/
function mint() external onlyOwner onlyWhenMintEnabled returns (uint256) {
uint256 newOriginalsSupply = originalsMinted.add(1);
require(
newOriginalsSupply <= MAX_SEEDS_SUPPLY,
"Max supply reached"
);
// The generated seed == the original nft token id.
// Both terms are used throughout and refer to the same thing.
uint256 seed = _generateSeed(newOriginalsSupply);
// Increment the supply per original nft (max: 1)
totalSupply[seed] = totalSupply[seed].add(1);
assert(totalSupply[seed] == 1);
// Update total originals minted
originalsMinted = newOriginalsSupply;
_mint(msg.sender, seed, 1, "");
emit MintOriginal(msg.sender, seed, newOriginalsSupply);
return seed;
}
/**
* @dev Function to mint prints from an existing seed. Msg.value must be sufficient.
* @param seed The NFT id to mint print of
* @param _owner The current owner of the seed
*/
function mintPrint(uint256 seed, address payable _owner)
external
payable
onlyWhenMintPrintEnabled
nonReentrant
returns (uint256)
{
// Confirm id is a seedId and belongs to _owner
require(isSeedId(seed) == true, "Invalid seed id");
// Confirm seed belongs to _owner
require(balanceOf(_owner, seed) == 1, "Incorrect seed owner");
// Spam-prevention: restrict msg.sender to only external accounts for an initial mintPrint period
if (msg.sender != tx.origin) {
require(_contractMintPrintEnabled == true, "Contracts not allowed to mintPrint");
}
// Derive print tokenId from seed
uint256 tokenId = getPrintTokenIdFromSeed(seed);
// Increment supply to compute current print price
uint256 newSupply = totalSupply[tokenId].add(1);
// Confirm newSupply does not exceed max
require(newSupply <= MAX_PRINT_SUPPLY, "Maximum supply exceeded");
// Get price to mint the next print
uint256 printPrice = getPrintPrice(newSupply);
require(msg.value >= printPrice, "Insufficient funds");
totalSupply[tokenId] = newSupply;
// Reserve cut is amount that will go towards reserve for burn at new supply
uint256 reserveCut = getBurnPrice(newSupply);
// Update reserve balance
reserve = reserve.add(reserveCut);
// Extract % for seed owner from difference between mintPrint cost and amount held for reserve
uint256 seedOwnerRoyalty = _getSeedOwnerCut(printPrice.sub(reserveCut));
// Mint token
_mint(msg.sender, tokenId, 1, "");
// Disburse royalties
if (seedOwnerRoyalty > 0) {
_distributeRoyalty(seed, _owner, seedOwnerRoyalty);
}
// If buyer sent extra ETH as padding in case another purchase was made they are refunded
_refundSender(printPrice);
emit PrintMinted(msg.sender, tokenId, seed, printPrice, getPrintPrice(newSupply.add(1)), reserveCut, newSupply, seedOwnerRoyalty, reserve, _owner);
return tokenId;
}
/**
* @dev Function to burn a print
* @param seed The seed for the print to burn.
* @param minimumSupply The minimum token supply for burn to succeed, this is a way to set slippage.
* Set to 1 to allow burn to go through no matter what the price is.
*/
function burnPrint(uint256 seed, uint256 minimumSupply) external onlyWhenBurnPrintEnabled nonReentrant {
// Confirm is valid seed id
require(isSeedId(seed) == true, "Invalid seed id");
// Derive token Id from seed
uint256 tokenId = getPrintTokenIdFromSeed(seed);
// Supply must meet user's minimum threshold
uint256 oldSupply = totalSupply[tokenId];
require(oldSupply >= minimumSupply, 'Min supply not met');
// burnPrice is the amount of ETH returned for burning this print
uint256 burnPrice = getBurnPrice(oldSupply);
uint256 newSupply = totalSupply[tokenId].sub(1);
totalSupply[tokenId] = newSupply;
// Update reserve balances
reserve = reserve.sub(burnPrice);
_burn(msg.sender, tokenId, 1);
// Disburse funds
msg.sender.sendValue(burnPrice);
emit PrintBurned(msg.sender, tokenId, seed, burnPrice, getPrintPrice(oldSupply), getBurnPrice(newSupply), newSupply, reserve);
}
/***********************************|
| Public Getters - Pricing |
|__________________________________*/
/**
* @dev Function to get print price
* @param printNumber the print number of the print Ex. if there are 2 existing prints, and you want to get the
* next print price, then this should be 3 as you are getting the price to mint the 3rd print
*/
function getPrintPrice(uint256 printNumber) public pure returns (uint256 price) {
uint256 decimals = 10 ** SIG_DIGITS;
// For prints 0-100, exponent value is < 0.001
if (printNumber <= 100) {
price = 0;
} else if (printNumber < B) {
// 10/A ^ (B - X)
price = (10 ** ( B.sub(printNumber) )).mul(decimals).div(A ** ( B.sub(printNumber)));
} else if (printNumber == B) {
// A/10 ^ 0 == 1
price = decimals; // price = decimals * (A ^ 0)
} else {
// A/10 ^ (X - B)
price = (A ** ( printNumber.sub(B) )).mul(decimals).div(10 ** ( printNumber.sub(B) ));
}
// += C*X
price = price.add(C.mul(printNumber));
// Convert to wei
price = price.mul(1 ether).div(decimals);
}
/**
* @dev Function to return amount of funds received when burned
* @param supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds
* receive on burn the supply should be 2
*/
function getBurnPrice(uint256 supply) public pure returns (uint256 price) {
uint256 printPrice = getPrintPrice(supply);
// 84 % of print price
price = printPrice.mul(84).div(100);
}
/**
* @dev Function to get prices by supply
* @param supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds
* receive on burn the supply should be 2
*/
function getPricesBySupply(uint256 supply) public pure returns (uint256 printPrice, uint256 nextPrintPrice, uint256 burnPrice, uint256 nextBurnPrice) {
printPrice = getPrintPrice(supply);
nextPrintPrice = getPrintPrice(supply + 1);
burnPrice = getBurnPrice(supply);
nextBurnPrice = getBurnPrice(supply + 1);
}
/**
* @dev Function to get prices & supply by seed
* @param seed The original NFT token id
*/
function getPricesBySeed(uint256 seed) external view returns (uint256 printPrice, uint256 nextPrintPrice, uint256 burnPrice, uint256 nextBurnPrice, uint256 supply) {
supply = seedToPrintsSupply(seed);
(printPrice, nextPrintPrice, burnPrice, nextBurnPrice) = getPricesBySupply(supply);
}
/***********************************|
| Public Getters - Seed + Prints |
|__________________________________*/
/**
* @dev Get the number of prints minted for the corresponding seed
* @param seed The original NFT token id
*/
function seedToPrintsSupply(uint256 seed)
public
view
returns (uint256)
{
uint256 tokenId = getPrintTokenIdFromSeed(seed);
return totalSupply[tokenId];
}
/**
* @dev The token id for the prints contains the original NFT id
* @param seed The original NFT token id
*/
function getPrintTokenIdFromSeed(uint256 seed) public pure returns (uint256) {
return seed | PRINTS_FLAG_BIT;
}
/**
* @dev Return whether a tokenId is for an original
* @param tokenId The original NFT token id
*/
function isSeedId(uint256 tokenId) public pure returns (bool) {
return tokenId & PRINTS_FLAG_BIT != PRINTS_FLAG_BIT;
}
/***********************************|
| Public Getters - Metadata |
|__________________________________*/
/**
* @dev Return the script section for a particular index
* @param index The index of a script section
*/
function getScriptAtIndex(uint256 index) external view returns (string memory) {
require(index < scriptCount, "Index out of bounds");
return scripts[index];
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* @return URI string
*/
function uri(uint256 _id) external override view returns (string memory) {
require(totalSupply[_id] > 0, "URI query for nonexistent token");
return string(abi.encodePacked(_baseURI, _id.toString(), ".json"));
}
/***********************************|
|Internal Functions - Generate Seed |
|__________________________________*/
/**
* @dev Returns a new seed
* @param uniqueValue Random input for the seed generation
*/
function _generateSeed(uint256 uniqueValue) internal view returns (uint256) {
bytes32 hash = keccak256(abi.encodePacked(block.number, blockhash(block.number.sub(1)), msg.sender, uniqueValue));
// gridLength 0-5
uint8 gridLength = uint8(hash[0]) % 15;
if (gridLength > 5) gridLength = 1;
// horizontalLever 0-58
uint8 horizontalLever = uint8(hash[1]) % 59;
// diagonalLever 0-10
uint8 diagonalLever = uint8(hash[2]) % 11;
// palette 4 0-11
uint8 palette = uint8(hash[3]) % 12;
// innerShape 0-3 with rarity
uint8 innerShape = uint8(hash[4]) % 4;
return uint256(gridLength) << 40 | uint256(horizontalLever) << 32 | uint256(diagonalLever) << 24 | uint256(palette) << 16 | uint256(innerShape) << 8;
}
/***********************************|
| Internal Functions - Prints |
|__________________________________*/
/**
* @dev Returns the part of the mintPrint fee reserved for the seed owner royalty
* @param fee Amount of ETH not added to the contract reserve
*/
function _getSeedOwnerCut(uint256 fee) internal pure returns (uint256) {
// Seed owner and Treum split royalties 50/50
return fee.div(2);
}
/**
* @dev For mintPrint only, send remaining msg.value back to sender
* @param printPrice Cost to mint current print
*/
function _refundSender(uint256 printPrice) internal {
if (msg.value.sub(printPrice) > 0) {
msg.sender.sendValue(msg.value.sub(printPrice));
}
}
/***********************************|
| Admin |
|__________________________________*/
/**
* @dev Add a new section of the script
* @param _script String value of script or pointer
*/
function addScript(string memory _script) external onlyOwner onlyUnlocked {
scripts[scriptCount] = _script;
scriptCount = scriptCount.add(1);
}
/**
* @dev Overwrite a script section at a particular index
* @param _script String value of script or pointer
* @param index Index of the script to replace
*/
function updateScript(string memory _script, uint256 index) external onlyOwner onlyUnlocked {
require(index < scriptCount, "Index out of bounds");
scripts[index] = _script;
}
/**
* @dev Reset script index to zero, caller must be owner and the contract unlocked
*/
function resetScriptCount() external onlyOwner onlyUnlocked {
scriptCount = 0;
}
/**
* @dev Withdraw earned funds from original Nft sales and print fees. Cannot withdraw the reserve funds.
*/
function withdraw() external onlyOwner nonReentrant {
uint256 withdrawableFunds = address(this).balance.sub(reserve);
msg.sender.sendValue(withdrawableFunds);
}
/**
* @dev Function to enable/disable original minting
* @param enabled The flag to turn minting on or off
*/
function setMintEnabled(bool enabled) external onlyOwner {
mintEnabled = enabled;
}
/**
* @dev Function to enable/disable print minting
* @param enabled The flag to turn minting on or off
*/
function setMintPrintEnabled(bool enabled) external onlyOwner {
mintPrintEnabled = enabled;
}
/**
* @dev Function to enable/disable print burning
* @param enabled The flag to turn minting on or off
*/
function setBurnPrintEnabled(bool enabled) external onlyOwner {
burnPrintEnabled = enabled;
}
/**
* @dev Function to enable/disable print minting via contract
* @param enabled The flag to turn contract print minting on or off
*/
function setContractMintPrintEnabled(bool enabled) external onlyOwner {
_contractMintPrintEnabled = enabled;
}
/**
* @dev Function to lock/unlock the on-chain metadata
* @param locked The flag turn locked on
*/
function setLocked(bool locked) external onlyOwner onlyUnlocked {
_locked = locked;
}
/**
* @dev Function to update the base _uri for all tokens
* @param newuri The base uri string
*/
function setURI(string memory newuri) external onlyOwner {
_baseURI = newuri;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../utils/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
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;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
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);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
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);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
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];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
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] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) 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].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
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), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
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++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _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");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
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");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import "./IEulerBeatsRoyaltyReceiver.sol";
contract RoyaltyDistributor {
using Address for address payable;
function _distributeRoyalty(
uint256 tokenId,
address payable tokenOwner,
uint256 royalty
) internal {
require(royalty > 0, "Missing royalty");
// this logic is broken into three cases:
// case 1: tokenOwner is a contract that implements RoyaltyReciever
// case 2: tokenOwner is a contract but not a RoyaltyReceiver
// case 3: tokenOwner is not a contract
if (tokenOwner.isContract()) {
if (ERC165Checker.supportsInterface(tokenOwner, IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived.selector)) {
// case 1
require(address(this).balance >= royalty, "RoyaltyDistributor: insufficient balance");
try IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived{value: royalty}(address(this), tokenId, tokenOwner) returns (bytes4 response) {
if (response != IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived.selector) {
revert("IEulerBeatsRoyaltyReceiver rejected royalty");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("RoyaltyDistributor: royaltyReceived reverted");
}
} else {
// case 2
tokenOwner.sendValue(royalty);
}
} else {
// case 3
tokenOwner.sendValue(royalty);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/introspection/ERC165.sol";
interface IEulerBeatsRoyaltyReceiver is IERC165 {
/**
@dev Handles the receipt of a royalty payout for the given original EulerBeat.
The royalty amount is the ether in msg.value.
To accept the royalty, this must return
`bytes4(keccak256("royaltyReceived(address,uint256,address)"))`
Implementors should take care to do the bare minimum in this function as it is
called as part of the mintPrint function, and will raise the gas required for minting prints.
@param tokenAddress The token address of the EulerBeats contract that the royalty was paid from
@param tokenId The ID of token the royalty was paid for. This is always the original token id, not print token ids
@param tokenOwner The current owner of the specified token
@return `bytes4(keccak256("royaltyReceived(address,uint256,address)"))` if royalty accepted
*/
function royaltyReceived(
address tokenAddress,
uint256 tokenId,
address tokenOwner
)
external payable
returns(bytes4);
}
|
Function to get prices by supply supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds receive on burn the supply should be 2/
|
function getPricesBySupply(uint256 supply) public pure returns (uint256 printPrice, uint256 nextPrintPrice, uint256 burnPrice, uint256 nextBurnPrice) {
printPrice = getPrintPrice(supply);
nextPrintPrice = getPrintPrice(supply + 1);
burnPrice = getBurnPrice(supply);
nextBurnPrice = getBurnPrice(supply + 1);
}
| 20,060 |
/**
*Submitted for verification at Etherscan.io on 2022-04-28
*/
pragma solidity ^0.8.9;
// SPDX-License-Identifier: NONE
//
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
//
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.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 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;
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.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 ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @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 {}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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);
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
/**
* @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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Arrays.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;
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Snapshot.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.
*
* NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it
* return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this
* function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
*
* Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
* alternative consider {ERC20Votes}.
*
* ==== 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 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 = _getCurrentSnapshotId();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Get the current snapshotId
*/
function _getCurrentSnapshotId() internal view virtual returns (uint256) {
return _currentSnapshotId.current();
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view virtual 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 virtual returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// Update balance and/or total supply snapshots before the values are modified. This is implemented
// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// mint
_updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
// burn
_updateAccountSnapshot(from);
_updateTotalSupplySnapshot();
} else {
// transfer
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
}
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) {
require(snapshotId > 0, "ERC20Snapshot: id is 0");
require(snapshotId <= _getCurrentSnapshotId(), "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 = _getCurrentSnapshotId();
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];
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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);
}
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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");
}
}
}
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;
}
//
// QuickFarm V1
// CREATED FOR MUSK GOLD BY QUICKFARM
contract MuskGoldFarmV1 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////
// USER DEPOSIT DEFINITION
//////////////////////////////////////////
struct UserDeposit {
uint256 balance; // THE DEPOSITED NUMBER OF TOKENS BY THE USER
uint256 unlockTime; // TIME WHEN THE USER CAN WITHDRAW FUNDS (BASED ON EPOCH)
uint256 lastPayout; // BLOCK NUMBER OF THE LAST PAYOUT FOR THIS USER IN THIS POOL
uint256 totalEarned; // TOTAL NUMBER OF TOKENS THIS USER HAS EARNED
}
//////////////////////////////////////////
// REWARD POOL DEFINITION
//////////////////////////////////////////
struct RewardPool {
IERC20 depositToken; // ADDRESS OF DEPOSITED TOKEN CONTRACT
bool active; // DETERMINES WHETHER OR NOT THIS POOL IS USABLE
bool hidden; // FLAG FOR WHETHER UI SHOULD RENDER THIS
bool uniV2Lp; // SIGNIFIES A IUNISWAPV2PAIR
bool selfStake; // SIGNIFIES IF THIS IS A 'SINGLE SIDED' SELF STAKE
bytes32 lpOrigin; // ORIGIN OF LP TOKEN BEING DEPOSITED E.G. SUSHI, UNISWAP, PANCAKE - NULL IF NOT N LP TOKEN
uint256 lockSeconds; // HOW LONG UNTIL AN LP DEPOSIT CAN BE REMOVED IN SECONDS
bool lockEnforced; // DETERMINES WHETER TIME LOCKS ARE ENFORCED
uint256 rewardPerBlock; // HOW MANY TOKENS TO REWARD PER BLOCK FOR THIS POOL
bytes32 label; // TEXT LABEL STRICTLY FOR READABILITY AND RENDERING
bytes32 order; // DISPLAY/PRESENTATION ORDER OF THE POOL
uint256 depositSum; // SUM OF ALL DEPOSITED TOKENS IN THIS POOL
}
//////////////////////////////////////////
// USER FARM STATE DEFINITION
//////////////////////////////////////////
struct UserFarmState {
RewardPool[] pools; // REWARD POOLS
uint256[] balance; // DEPOSITS BY POOL
uint256[] unlockTime; // UNLOCK TIME FOR EACH POOL DEPOSIT
uint256[] pending; // PENDING REWARDS BY POOL
uint256[] earnings; // EARNINGS BY POOL
uint256[] depTknBal; // USER BALANCE OF DEPOSIT TOKEN
uint256[] depTknSupply; // TOTAL SUPPLY OF DEPOSIT TOKEN
uint256[] reserve0; // RESERVE0 AMOUNT FOR LP TKN0
uint256[] reserve1; // RESERVE1 AMOUNT FOR LP TKN1
address[] token0; // ADDRESS OF LP TOKEN 0
address[] token1; // ADDRESS OF LP TOKEN 1
uint256 rewardTknBal; // CURRENT USER HOLDINGS OF THE REWARD TOKEN
uint256 pendingAllPools; // REWARDS PENDING FOR ALL POOLS
uint256 earningsAllPools; // REWARDS EARNED FOR ALL POOLS
}
//////////////////////////////////////////
// INIT CLASS VARIABLES
//////////////////////////////////////////
bytes32 public name; // POOL NAME, FOR DISPLAY ON BLOCK EXPLORER
IERC20 public rewardToken; // ADDRESS OF THE ERC20 REWARD TOKEN
address public rewardWallet; // WALLE THAT REWARD TOKENS ARE DRAWN FROM
uint256 public earliestRewards; // EARLIEST BLOCK REWARDS CAN BE GENERATED FROM (FOR FAIR LAUNCH)
uint256 public paidOut = 0; // TOTAL AMOUNT OF REWARDS THAT HAVE BEEN PAID OUT
RewardPool[] public rewardPools; // INFO OF EACH POOL
address[] public depositAddresses; // LIST OF ADDRESSES THAT CURRENTLY HAVE FUNDS DEPOSITED
mapping(uint256 => mapping(address => UserDeposit)) public userDeposits; // INFO OF EACH USER THAT STAKES LP TOKENS
//////////////////////////////////////////
// EVENTS
//////////////////////////////////////////
event Deposit(
address indexed from,
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Reward(address indexed user, uint256 indexed pid, uint256 amount);
event Restake(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
//////////////////////////////////////////
// CONSTRUCTOR
//////////////////////////////////////////
constructor(
IERC20 _rewardToken,
address _rewardWallet,
uint256 _earliestRewards
) {
name = "Musk Gold Farm";
rewardToken = _rewardToken;
rewardWallet = _rewardWallet;
earliestRewards = _earliestRewards;
}
//////////////////////////////////////////
// FARM FUNDING CONTROLS
//////////////////////////////////////////
// SETS ADDRESS THAT REWARDS ARE TO BE PAID FROM
function setRewardWallet(address _source) external onlyOwner {
rewardWallet = _source;
}
// FUND THE FARM (JUST DEPOSITS FUNDS INTO THE REWARD WALLET)
function fund(uint256 _amount) external {
require(msg.sender != rewardWallet, "Sender is reward wallet");
rewardToken.safeTransferFrom(
address(msg.sender),
rewardWallet,
_amount
);
}
//////////////////////////////////////////
// POOL CONTROLS
//////////////////////////////////////////
// ADD LP TOKEN REWARD POOL
function addPool(
IERC20 _depositToken,
bool _active,
bool _hidden,
bool _uniV2Lp,
bytes32 _lpOrigin,
uint256 _lockSeconds,
bool _lockEnforced,
uint256 _rewardPerBlock,
bytes32 _label,
bytes32 _order
) external onlyOwner {
// MAKE SURE THIS REWARD POOL FOR TOKEN + LOCK DOESN'T ALREADY EXIST
require(
poolExists(_depositToken, _lockSeconds) == false,
"Reward pool for token already exists"
);
// IF TOKEN BEING DEPOSITED IS THE SAME AS THE REWARD TOKEN MARK IT AS A SELF STAKE (SINGLE SIDED)
bool selfStake = false;
if (_depositToken == rewardToken) {
selfStake = true;
_uniV2Lp = false;
}
rewardPools.push(
RewardPool({
depositToken: _depositToken,
active: _active,
hidden: _hidden,
uniV2Lp: _uniV2Lp,
selfStake: selfStake, // MARKS IF A "SINGLED SIDED" STAKE OF THE REWARD TOKEN
lpOrigin: _lpOrigin,
lockSeconds: _lockSeconds,
lockEnforced: _lockEnforced,
rewardPerBlock: _rewardPerBlock,
label: _label,
order: _order,
depositSum: 0
})
);
}
function setPool(
// MODIFY AN EXISTING POOL
uint256 _pid,
bool _active,
bool _hidden,
bool _uniV2Lp,
bytes32 _lpOrigin,
uint256 _lockSeconds,
bool _lockEnforced,
uint256 _rewardPerBlock,
bytes32 _label,
bytes32 _order
) external onlyOwner {
rewardPools[_pid].active = _active;
rewardPools[_pid].hidden = _hidden;
rewardPools[_pid].uniV2Lp = _uniV2Lp;
rewardPools[_pid].lpOrigin = _lpOrigin;
rewardPools[_pid].lockSeconds = _lockSeconds;
rewardPools[_pid].lockEnforced = _lockEnforced;
rewardPools[_pid].rewardPerBlock = _rewardPerBlock;
rewardPools[_pid].label = _label;
rewardPools[_pid].order = _order;
}
// PAUSES/RESUMES DEPOSITS FOR ALL POOLS
function setFarmActive(bool _value) public onlyOwner {
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
RewardPool storage pool = rewardPools[pid];
pool.active = _value;
}
}
// SETS THE EARLIEST BLOCK FROM WHICH TO CALCULATE REWARDS
function setEarliestRewards(uint256 _value) external onlyOwner {
require(
_value >= block.number,
"Earliest reward block must be greater than the current block"
);
earliestRewards = _value;
}
//////////////////////////////////////////
// DEPOSIT/WITHDRAW METHODS
//////////////////////////////////////////
// SETS THE "LAST PAYOUT" FOR A USER TO ULTIMATELY DETERMINE HOW MANY REWARDS THEY ARE OWED
function setLastPayout(UserDeposit storage _deposit) private {
_deposit.lastPayout = block.number;
if (_deposit.lastPayout < earliestRewards)
_deposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION
}
// DEPOSIT TOKENS (LP OR SIMPLE ERC20) FOR A GIVEN TARGET (USER) WALLET
function deposit(
uint256 _pid,
address _user,
uint256 _amount
) public nonReentrant {
RewardPool storage pool = rewardPools[_pid];
require(_amount > 0, "Amount must be greater than zero");
require(pool.active == true, "This reward pool is inactive");
UserDeposit storage userDeposit = userDeposits[_pid][_user];
// SET INITIAL LAST PAYOUT
if (userDeposit.lastPayout == 0) {
userDeposit.lastPayout = block.number;
if (userDeposit.lastPayout < earliestRewards)
userDeposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION
}
// COLLECT REWARD ONLY IF ADDRESS DEPOSITING IS THE OWNER OF THE DEPOSIT
if (userDeposit.balance > 0 && msg.sender == _user) {
payReward(_pid, _user);
}
pool.depositToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
); // DO THE ACTUAL DEPOSIT
userDeposit.balance = userDeposit.balance.add(_amount); // ADD THE TRANSFERRED AMOUNT TO THE DEPOSIT VALUE
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // UPDATE THE UNLOCK TIME
pool.depositSum = pool.depositSum.add(_amount); // KEEP TRACK OF TOTAL DEPOSITS IN THE POOL
recordAddress(_user); // RECORD THE USER ADDRESS IN THE LIST
emit Deposit(msg.sender, _user, _pid, _amount);
}
// PRIVATE METHOD TO PAY OUT USER REWARDS
function payReward(uint256 _pid, address _user) private {
UserDeposit storage userDeposit = userDeposits[_pid][_user]; // FETCH THE DEPOSIT
uint256 rewardsDue = userPendingPool(_pid, _user); // GET PENDING REWARDS
if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARD IS DUE
rewardToken.transferFrom(rewardWallet, _user, rewardsDue);
emit Reward(_user, _pid, rewardsDue);
userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD THE PAYOUT AMOUNT TO TOTAL EARNINGS
paidOut = paidOut.add(rewardsDue); // ADD AMOUNT TO TOTAL PAIDOUT FOR THE WHOLE FARM
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
}
// EXTERNAL METHOD FOR USER'S TO COLLECT REWARDS
function collectReward(uint256 _pid) external nonReentrant {
payReward(_pid, msg.sender);
}
// RESTAKE REWARDS INTO SINGLE-SIDED POOLS
function restake(uint256 _pid) external nonReentrant {
RewardPool storage pool = rewardPools[_pid]; // GET THE POOL
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; // FETCH THE DEPOSIT
require(
pool.depositToken == rewardToken,
"Restake is only available on single-sided staking"
);
uint256 rewardsDue = userPendingPool(_pid, msg.sender); // GET PENDING REWARD AMOUNT
if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARDS ARE TO BE PAID
pool.depositToken.safeTransferFrom(
rewardWallet,
address(this),
rewardsDue
); // MOVE FUNDS FROM THE REWARDS TO THIS CONTRACT
pool.depositSum = pool.depositSum.add(rewardsDue);
userDeposit.balance = userDeposit.balance.add(rewardsDue); // ADD THE FUNDS MOVED TO THE USER'S BALANCE
userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD FUNDS MOVED TO USER'S TOTAL EARNINGS FOR POOL
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
paidOut = paidOut.add(rewardsDue); // ADD TO THE TOTAL PAID OUT FOR THE FARM
emit Restake(msg.sender, _pid, rewardsDue);
}
// WITHDRAW LP TOKENS FROM FARM.
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
RewardPool storage pool = rewardPools[_pid];
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender];
if (pool.lockEnforced)
require(
userDeposit.unlockTime <= block.timestamp,
"withdraw: time lock has not passed"
);
require(
userDeposit.balance >= _amount,
"withdraw: can't withdraw more than deposit"
);
payReward(_pid, msg.sender); // PAY OUT ANY REWARDS ACCUMULATED UP TO THIS POINT
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME
userDeposit.balance = userDeposit.balance.sub(_amount); // SUBTRACT THE AMOUNT DEBITED FROM THE BALANCE
pool.depositToken.safeTransfer(address(msg.sender), _amount); // TRANSFER THE WITHDRAWN AMOUNT BACK TO THE USER
emit Withdraw(msg.sender, _pid, _amount);
pool.depositSum = pool.depositSum.sub(_amount); // SUBTRACT THE WITHDRAWN AMOUNT FROM THE POOL DEPOSIT TOTAL
cleanupAddress(msg.sender);
}
// APPEND ADDRESSES THAT HAVE FUNDS DEPOSITED FOR EASY RETRIEVAL
function recordAddress(address _address) private {
for (uint256 i = 0; i < depositAddresses.length; i++) {
address curAddress = depositAddresses[i];
if (_address == curAddress) return;
}
depositAddresses.push(_address);
}
// CLEAN ANY ADDRESSES THAT DON'T HAVE ACTIVE DEPOSITS
function cleanupAddress(address _address) private {
// CHECK TO SEE IF THE ADDRESS HAS ANY DEPOSITS
uint256 deposits = 0;
for (uint256 pid = 0; pid < rewardPools.length; pid++) {
deposits = deposits.add(userDeposits[pid][_address].balance);
}
if (deposits > 0) return; // BAIL OUT IF USER STILL HAS DEPOSITS
for (uint256 i = 0; i < depositAddresses.length; i++) {
address curAddress = depositAddresses[i];
if (_address == curAddress) delete depositAddresses[i]; // REMOVE ADDRESS FROM ARRAY
}
}
//////////////////////////////////////////
// INFORMATION METHODS
//////////////////////////////////////////
// RETURNS THE ARRAY OF POOLS
function getPools() public view returns (RewardPool[] memory) {
return rewardPools;
}
// RETURNS REWARD TOKENS REMAINING
function rewardsRemaining() public view returns (uint256) {
return rewardToken.balanceOf(rewardWallet);
}
// RETURNS COUNT OF ADDRESSES WITH DEPOSITS
function addressCount() external view returns (uint256) {
return depositAddresses.length;
}
// CHECK IF A GIVEN DEPOSIT TOKEN + TIMELOCK COMBINATION ALREADY EXISTS
function poolExists(IERC20 _depositToken, uint256 _lockSeconds)
private
view
returns (bool)
{
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
RewardPool storage pool = rewardPools[pid];
if (
pool.depositToken == _depositToken &&
pool.lockSeconds == _lockSeconds
) return true;
}
return false;
}
// RETURNS COUNT OF LP POOLS
function poolLength() external view returns (uint256) {
return rewardPools.length;
}
// RETURNS SUM OF DEPOSITS IN X POOL
function poolDepositSum(uint256 _pid) external view returns (uint256) {
return rewardPools[_pid].depositSum;
}
// VIEW FUNCTION TO SEE PENDING REWARDS FOR A USER
function userPendingPool(uint256 _pid, address _user)
public
view
returns (uint256)
{
RewardPool storage pool = rewardPools[_pid];
UserDeposit storage userDeposit = userDeposits[_pid][_user];
if (userDeposit.balance == 0) return 0;
if (earliestRewards > block.number) return 0;
uint256 precision = 1e36;
uint256 blocksElapsed = 0;
if (block.number > userDeposit.lastPayout)
blocksElapsed = block.number.sub(userDeposit.lastPayout);
uint256 poolOwnership = userDeposit.balance.mul(precision).div(
pool.depositSum
);
uint256 rewardsDue = blocksElapsed
.mul(pool.rewardPerBlock)
.mul(poolOwnership)
.div(precision);
return rewardsDue;
}
// GETS PENDING REWARDS FOR A GIVEN USER IN ALL POOLS
function userPendingAll(address _user) public view returns (uint256) {
uint256 totalReward = 0;
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
uint256 pending = userPendingPool(pid, _user);
totalReward = totalReward.add(pending);
}
return totalReward;
}
// RETURNS TOTAL PAID OUT TO A USER FOR A GIVEN POOL
function userEarnedPool(uint256 _pid, address _user)
public
view
returns (uint256)
{
return userDeposits[_pid][_user].totalEarned;
}
// RETURNS USER EARNINGS FOR ALL POOLS
function userEarnedAll(address _user) public view returns (uint256) {
uint256 totalEarned = 0;
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
totalEarned = totalEarned.add(userDeposits[pid][_user].totalEarned);
}
return totalEarned;
}
// VIEW FUNCTION FOR TOTAL REWARDS THE FARM HAS YET TO PAY OUT
function farmTotalPending() external view returns (uint256) {
uint256 pending = 0;
for (uint256 i = 0; i < depositAddresses.length; ++i) {
uint256 userPending = userPendingAll(depositAddresses[i]);
pending = pending.add(userPending);
}
return pending;
}
// RETURNS A GIVEN USER'S STATE IN THE FARM IN A SINGLE CALL
function getUserState(address _user)
external
view
returns (UserFarmState memory)
{
uint256[] memory balance = new uint256[](rewardPools.length);
uint256[] memory pending = new uint256[](rewardPools.length);
uint256[] memory earned = new uint256[](rewardPools.length);
uint256[] memory depTknBal = new uint256[](rewardPools.length);
uint256[] memory depTknSupply = new uint256[](rewardPools.length);
uint256[] memory depTknReserve0 = new uint256[](rewardPools.length);
uint256[] memory depTknReserve1 = new uint256[](rewardPools.length);
address[] memory depTknResTkn0 = new address[](rewardPools.length);
address[] memory depTknResTkn1 = new address[](rewardPools.length);
uint256[] memory unlockTime = new uint256[](rewardPools.length);
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
balance[pid] = userDeposits[pid][_user].balance;
pending[pid] = userPendingPool(pid, _user);
earned[pid] = userEarnedPool(pid, _user);
depTknBal[pid] = rewardPools[pid].depositToken.balanceOf(_user);
depTknSupply[pid] = rewardPools[pid].depositToken.totalSupply();
unlockTime[pid] = userDeposits[pid][_user].unlockTime;
if (
rewardPools[pid].uniV2Lp == true &&
rewardPools[pid].selfStake == false
) {
IUniswapV2Pair pair = IUniswapV2Pair(
address(rewardPools[pid].depositToken)
);
(uint256 res0, uint256 res1, uint256 timestamp) = pair
.getReserves();
depTknReserve0[pid] = res0;
depTknReserve1[pid] = res1;
depTknResTkn0[pid] = pair.token0();
depTknResTkn1[pid] = pair.token1();
}
}
return
UserFarmState(
rewardPools, // POOLS
balance, // DEPOSITS BY POOL
unlockTime, // UNLOCK TIME FOR EACH DEPOSITED POOL
pending, // PENDING REWARDS BY POOL
earned, // EARNINGS BY POOL
depTknBal, // USER BALANCE OF DEPOSIT TOKEN
depTknSupply, // TOTAL SUPPLY OF DEPOSIT TOKEN
depTknReserve0, // RESERVE0 AMOUNT FOR LP TKN0
depTknReserve1, // RESERVE1 AMOUNT FOR LP TKN1
depTknResTkn0, // ADDRESS OF LP TOKEN 0
depTknResTkn1, // ADDRESS OF LP TOKEN 1
rewardToken.balanceOf(_user), // CURRENT USER HOLDINGS OF THE REWARD TOKEN
userPendingAll(_user), // REWARDS PENDING FOR ALL POOLS
userEarnedAll(_user) // REWARDS EARNED FOR ALL POOLS
);
}
//////////////////////////////////////////
// EMERGENCY CONTROLS
//////////////////////////////////////////
// WITHDRAW WITHOUT CARING ABOUT REWARDS. EMERGENCY ONLY.
// THIS WILL WIPE OUT ANY PENDING REWARDS FOR A USER
function emergencyWithdraw(uint256 _pid) external nonReentrant {
RewardPool storage pool = rewardPools[_pid]; // GET THE POOL
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; //GET THE DEPOSIT
pool.depositToken.safeTransfer(
address(msg.sender),
userDeposit.balance
); // TRANSFER THE DEPOSIT BACK TO THE USER
pool.depositSum = pool.depositSum.sub(userDeposit.balance); // DECREMENT THE POOL'S OVERALL DEPOSIT SUM
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME
userDeposit.balance = 0; // SET THE BALANCE TO ZERO AFTER WIRTHDRAWAL
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
emit EmergencyWithdraw(msg.sender, _pid, userDeposit.balance);
}
}
|
PRIVATE METHOD TO PAY OUT USER REWARDS
|
function payReward(uint256 _pid, address _user) private {
rewardToken.transferFrom(rewardWallet, _user, rewardsDue);
emit Reward(_user, _pid, rewardsDue);
}
| 7,938,609 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "../interfaces/IERC20.sol";
import "../libraries/History.sol";
import "../libraries/VestingVaultStorage.sol";
import "../libraries/Storage.sol";
import "../interfaces/IVotingVault.sol";
abstract contract AbstractVestingVault is IVotingVault {
// Bring our libraries into scope
using History for *;
using VestingVaultStorage for *;
using Storage for *;
// NOTE: There is no emergency withdrawal, any funds not sent via deposit() are
// unrecoverable by this version of the VestingVault
// This contract has a privileged grant manager who can add grants or remove grants
// It will not transfer in on each grant but rather check for solvency via state variables.
// Immutables are in bytecode so don't need special storage treatment
IERC20 public immutable token;
// A constant which is how far back stale blocks are
uint256 public immutable staleBlockLag;
event VoteChange(address indexed to, address indexed from, int256 amount);
/// @notice Constructs the contract.
/// @param _token The erc20 token to grant.
/// @param _stale Stale block used for voting power calculations.
constructor(IERC20 _token, uint256 _stale) {
token = _token;
staleBlockLag = _stale;
}
/// @notice initialization function to set initial variables.
/// @dev Can only be called once after deployment.
/// @param manager_ The vault manager can add and remove grants.
/// @param timelock_ The timelock address can change the unvested multiplier.
function initialize(address manager_, address timelock_) public {
require(Storage.uint256Ptr("initialized").data == 0, "initialized");
Storage.set(Storage.uint256Ptr("initialized"), 1);
Storage.set(Storage.addressPtr("manager"), manager_);
Storage.set(Storage.addressPtr("timelock"), timelock_);
Storage.set(Storage.uint256Ptr("unvestedMultiplier"), 100);
}
// deposits mapping(address => Grant)
/// @notice A single function endpoint for loading grant storage
/// @dev Only one Grant is allowed per address. Grants SHOULD NOT
/// be modified.
/// @return returns a storage mapping which can be used to look up grant data
function _grants()
internal
pure
returns (mapping(address => VestingVaultStorage.Grant) storage)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return (VestingVaultStorage.mappingAddressToGrantPtr("grants"));
}
/// @notice A single function endpoint for loading the starting
/// point of the range for each accepted grant
/// @dev This is modified any time a grant is accepted
/// @return returns the starting point uint
function _loadBound() internal pure returns (Storage.Uint256 memory) {
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return Storage.uint256Ptr("bound");
}
/// @notice A function to access the storage of the unassigned token value
/// @dev The unassigned tokens are not part of any grant and ca be used
/// for a future grant or withdrawn by the manager.
/// @return A struct containing the unassigned uint.
function _unassigned() internal pure returns (Storage.Uint256 storage) {
return Storage.uint256Ptr("unassigned");
}
/// @notice A function to access the storage of the manager address.
/// @dev The manager can access all functions with the onlyManager modifier.
/// @return A struct containing the manager address.
function _manager() internal pure returns (Storage.Address memory) {
return Storage.addressPtr("manager");
}
/// @notice A function to access the storage of the timelock address
/// @dev The timelock can access all functions with the onlyTimelock modifier.
/// @return A struct containing the timelock address.
function _timelock() internal pure returns (Storage.Address memory) {
return Storage.addressPtr("timelock");
}
/// @notice A function to access the storage of the unvestedMultiplier value
/// @dev The unvested multiplier is a number that represents the voting power of each
/// unvested token as a percentage of a vested token. For example if
/// unvested tokens have 50% voting power compared to vested ones, this value would be 50.
/// This can be changed by governance in the future.
/// @return A struct containing the unvestedMultiplier uint.
function _unvestedMultiplier()
internal
pure
returns (Storage.Uint256 memory)
{
return Storage.uint256Ptr("unvestedMultiplier");
}
modifier onlyManager() {
require(msg.sender == _manager().data, "!manager");
_;
}
modifier onlyTimelock() {
require(msg.sender == _timelock().data, "!timelock");
_;
}
/// @notice Getter for the grants mapping
/// @param _who The owner of the grant to query
/// @return Grant of the provided address
function getGrant(address _who)
external
view
returns (VestingVaultStorage.Grant memory)
{
return _grants()[_who];
}
/// @notice Accepts a grant
/// @dev Sends token from the contract to the sender and back to the contract
/// while assigning a numerical range to the unwithdrawn granted tokens.
function acceptGrant() public {
// load the grant
VestingVaultStorage.Grant storage grant = _grants()[msg.sender];
uint256 availableTokens = grant.allocation - grant.withdrawn;
// check that grant has unwithdrawn tokens
require(availableTokens > 0, "no grant available");
// transfer the token to the user
token.transfer(msg.sender, availableTokens);
// transfer from the user back to the contract
token.transferFrom(msg.sender, address(this), availableTokens);
uint256 bound = _loadBound().data;
grant.range = [bound, bound + availableTokens];
Storage.set(Storage.uint256Ptr("bound"), bound + availableTokens);
}
/// @notice Adds a new grant.
/// @dev Manager can set who the voting power will be delegated to initially.
/// This potentially avoids the need for a delegation transaction by the grant recipient.
/// @param _who The Grant recipient.
/// @param _amount The total grant value.
/// @param _startTime Optionally set a non standard start time. If set to zero then the start time
/// will be made the block this is executed in.
/// @param _expiration timestamp when the grant ends (all tokens count as unlocked).
/// @param _cliff Timestamp when the cliff ends. No tokens are unlocked until this
/// timestamp is reached.
/// @param _delegatee Optional param. The address to delegate the voting power
/// associated with this grant to
function addGrantAndDelegate(
address _who,
uint128 _amount,
uint128 _startTime,
uint128 _expiration,
uint128 _cliff,
address _delegatee
) public onlyManager {
// Consistency check
require(
_cliff <= _expiration && _startTime <= _expiration,
"Invalid configuration"
);
// If no custom start time is needed we use this block.
if (_startTime == 0) {
_startTime = uint128(block.number);
}
Storage.Uint256 storage unassigned = _unassigned();
Storage.Uint256 memory unvestedMultiplier = _unvestedMultiplier();
require(unassigned.data >= _amount, "Insufficient balance");
// load the grant.
VestingVaultStorage.Grant storage grant = _grants()[_who];
// If this address already has a grant, a different address must be provided
// topping up or editing active grants is not supported.
require(grant.allocation == 0, "Has Grant");
// load the delegate. Defaults to the grant owner
_delegatee = _delegatee == address(0) ? _who : _delegatee;
// calculate the voting power. Assumes all voting power is initially locked.
// Come back to this assumption.
uint128 newVotingPower =
(_amount * uint128(unvestedMultiplier.data)) / 100;
// set the new grant
_grants()[_who] = VestingVaultStorage.Grant(
_amount,
0,
_startTime,
_expiration,
_cliff,
newVotingPower,
_delegatee,
[uint256(0), uint256(0)]
);
// update the amount of unassigned tokens
unassigned.data -= _amount;
// update the delegatee's voting power
History.HistoricalBalances memory votingPower = _votingPower();
uint256 delegateeVotes = votingPower.loadTop(grant.delegatee);
votingPower.push(grant.delegatee, delegateeVotes + newVotingPower);
emit VoteChange(grant.delegatee, _who, int256(uint256(newVotingPower)));
}
/// @notice Removes a grant.
/// @dev The manager has the power to remove a grant at any time. Any withdrawable tokens will be
/// sent to the grant owner.
/// @param _who The Grant owner.
function removeGrant(address _who) public virtual onlyManager {
// load the grant
VestingVaultStorage.Grant storage grant = _grants()[_who];
// get the amount of withdrawable tokens
uint256 withdrawable = _getWithdrawableAmount(grant);
// it is simpler to just transfer withdrawable tokens instead of modifying the struct storage
// to allow withdrawal through claim()
token.transfer(_who, withdrawable);
Storage.Uint256 storage unassigned = _unassigned();
uint256 locked = grant.allocation - (grant.withdrawn + withdrawable);
// return the unused tokens so they can be used for a different grant
unassigned.data += locked;
// update the delegatee's voting power
History.HistoricalBalances memory votingPower = _votingPower();
uint256 delegateeVotes = votingPower.loadTop(grant.delegatee);
votingPower.push(
grant.delegatee,
delegateeVotes - grant.latestVotingPower
);
// Emit the vote change event
emit VoteChange(
grant.delegatee,
_who,
-1 * int256(uint256(grant.latestVotingPower))
);
// delete the grant
delete _grants()[_who];
}
/// @notice Claim all withdrawable value from a grant.
/// @dev claiming value resets the voting power, This could either increase or reduce the
/// total voting power associated with the caller's grant.
function claim() public virtual {
// load the grant
VestingVaultStorage.Grant storage grant = _grants()[msg.sender];
// get the withdrawable amount
uint256 withdrawable = _getWithdrawableAmount(grant);
// transfer the available amount
token.transfer(msg.sender, withdrawable);
grant.withdrawn += uint128(withdrawable);
// only move range bound if grant was accepted
if (grant.range[1] > 0) {
grant.range[1] -= withdrawable;
}
// update the user's voting power
_syncVotingPower(msg.sender, grant);
}
/// @notice Changes the caller's token grant voting power delegation.
/// @dev The total voting power is not guaranteed to go up because
/// the unvested token multiplier can be updated at any time.
/// @param _to the address to delegate to
function delegate(address _to) public {
VestingVaultStorage.Grant storage grant = _grants()[msg.sender];
// If the delegation has already happened we don't want the tx to send
require(_to != grant.delegatee, "Already delegated");
History.HistoricalBalances memory votingPower = _votingPower();
uint256 oldDelegateeVotes = votingPower.loadTop(grant.delegatee);
uint256 newVotingPower = _currentVotingPower(grant);
// Remove old delegatee's voting power and emit event
votingPower.push(
grant.delegatee,
oldDelegateeVotes - grant.latestVotingPower
);
emit VoteChange(
grant.delegatee,
msg.sender,
-1 * int256(uint256(grant.latestVotingPower))
);
// Note - It is important that this is loaded here and not before the previous state change because if
// _to == grant.delegatee and re-delegation was allowed we could be working with out of date state.
uint256 newDelegateeVotes = votingPower.loadTop(_to);
// add voting power to the target delegatee and emit event
emit VoteChange(_to, msg.sender, int256(newVotingPower));
votingPower.push(_to, newDelegateeVotes + newVotingPower);
// update grant info
grant.latestVotingPower = uint128(newVotingPower);
grant.delegatee = _to;
}
/// @notice Manager-only token deposit function.
/// @dev Deposited tokens are added to `_unassigned` and can be used to create grants.
/// WARNING: This is the only way to deposit tokens into the contract. Any tokens sent
/// via other means are not recoverable by this contract.
/// @param _amount The amount of tokens to deposit.
function deposit(uint256 _amount) public onlyManager {
Storage.Uint256 storage unassigned = _unassigned();
// update unassigned value
unassigned.data += _amount;
token.transferFrom(msg.sender, address(this), _amount);
}
/// @notice Manager-only token withdrawal function.
/// @dev The manager can withdraw tokens that are not being used by a grant.
/// This function cannot be used to recover tokens that were sent to this contract
/// by any means other than `deposit()`
/// @param _amount the amount to withdraw
/// @param _recipient the address to withdraw to
function withdraw(uint256 _amount, address _recipient)
public
virtual
onlyManager
{
Storage.Uint256 storage unassigned = _unassigned();
require(unassigned.data >= _amount, "Insufficient balance");
// update unassigned value
unassigned.data -= _amount;
token.transfer(_recipient, _amount);
}
/// @notice Update a delegatee's voting power.
/// @dev Voting power is only updated for this block onward.
/// see `History` for more on how voting power is tracked and queried.
/// Anybody can update a grant's voting power.
/// @param _who the address who's voting power this function updates
function updateVotingPower(address _who) public {
VestingVaultStorage.Grant storage grant = _grants()[_who];
_syncVotingPower(_who, grant);
}
/// @notice Helper to update a delegatee's voting power.
/// @param _who the address who's voting power we need to sync
/// @param _grant the storage pointer to the grant of that user
function _syncVotingPower(
address _who,
VestingVaultStorage.Grant storage _grant
) internal {
History.HistoricalBalances memory votingPower = _votingPower();
uint256 delegateeVotes = votingPower.loadTop(_grant.delegatee);
uint256 newVotingPower = _currentVotingPower(_grant);
// get the change in voting power. Negative if the voting power is reduced
int256 change =
int256(newVotingPower) - int256(uint256(_grant.latestVotingPower));
// do nothing if there is no change
if (change == 0) return;
if (change > 0) {
votingPower.push(
_grant.delegatee,
delegateeVotes + uint256(change)
);
} else {
// if the change is negative, we multiply by -1 to avoid underflow when casting
votingPower.push(
_grant.delegatee,
delegateeVotes - uint256(change * -1)
);
}
emit VoteChange(_grant.delegatee, _who, change);
_grant.latestVotingPower = uint128(newVotingPower);
}
/// @notice Attempts to load the voting power of a user
/// @param user The address we want to load the voting power of
/// @param blockNumber the block number we want the user's voting power at
// @param calldata the extra calldata is unused in this contract
/// @return the number of votes
function queryVotePower(
address user,
uint256 blockNumber,
bytes calldata
) external override returns (uint256) {
// Get our reference to historical data
History.HistoricalBalances memory votingPower = _votingPower();
// Find the historical data and clear everything more than 'staleBlockLag' into the past
return
votingPower.findAndClear(
user,
blockNumber,
block.number - staleBlockLag
);
}
/// @notice Loads the voting power of a user without changing state
/// @param user The address we want to load the voting power of
/// @param blockNumber the block number we want the user's voting power at
/// @return the number of votes
function queryVotePowerView(address user, uint256 blockNumber)
external
view
returns (uint256)
{
// Get our reference to historical data
History.HistoricalBalances memory votingPower = _votingPower();
// Find the historical data
return votingPower.find(user, blockNumber);
}
/// @notice Calculates how much a grantee can withdraw
/// @param _grant the memory location of the loaded grant
/// @return the amount which can be withdrawn
function _getWithdrawableAmount(VestingVaultStorage.Grant memory _grant)
internal
view
returns (uint256)
{
if (block.number < _grant.cliff || block.number < _grant.created) {
return 0;
}
if (block.number >= _grant.expiration) {
return (_grant.allocation - _grant.withdrawn);
}
uint256 unlocked =
(_grant.allocation * (block.number - _grant.created)) /
(_grant.expiration - _grant.created);
return (unlocked - _grant.withdrawn);
}
/// @notice Returns the historical voting power tracker.
/// @return A struct which can push to and find items in block indexed storage.
function _votingPower()
internal
pure
returns (History.HistoricalBalances memory)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout.
return (History.load("votingPower"));
}
/// @notice Helper that returns the current voting power of a grant
/// @dev This is not always the recorded voting power since it uses the latest
/// _unvestedMultiplier.
/// @param _grant The grant to check for voting power.
/// @return The current voting power of the grant.
function _currentVotingPower(VestingVaultStorage.Grant memory _grant)
internal
view
returns (uint256)
{
uint256 withdrawable = _getWithdrawableAmount(_grant);
uint256 locked = _grant.allocation - (withdrawable + _grant.withdrawn);
return (withdrawable + (locked * _unvestedMultiplier().data) / 100);
}
/// @notice timelock-only unvestedMultiplier update function.
/// @dev Allows the timelock to update the unvestedMultiplier.
/// @param _multiplier The new multiplier.
function changeUnvestedMultiplier(uint256 _multiplier) public onlyTimelock {
require(_multiplier <= 100, "Above 100%");
Storage.set(Storage.uint256Ptr("unvestedMultiplier"), _multiplier);
}
/// @notice timelock-only timelock update function.
/// @dev Allows the timelock to update the timelock address.
/// @param timelock_ The new timelock.
function setTimelock(address timelock_) public onlyTimelock {
Storage.set(Storage.addressPtr("timelock"), timelock_);
}
/// @notice timelock-only manager update function.
/// @dev Allows the timelock to update the manager address.
/// @param manager_ The new manager.
function setManager(address manager_) public onlyTimelock {
Storage.set(Storage.addressPtr("manager"), manager_);
}
/// @notice A function to access the storage of the timelock address
/// @dev The timelock can access all functions with the onlyTimelock modifier.
/// @return The timelock address.
function timelock() public pure returns (address) {
return _timelock().data;
}
/// @notice A function to access the storage of the unvested token vote power multiplier.
/// @return The unvested token multiplier
function unvestedMultiplier() external pure returns (uint256) {
return _unvestedMultiplier().data;
}
/// @notice A function to access the storage of the manager address.
/// @dev The manager can access all functions with the olyManager modifier.
/// @return The manager address.
function manager() public pure returns (address) {
return _manager().data;
}
}
// Deployable version of the abstract contract
contract VestingVault is AbstractVestingVault {
/// @notice Constructs the contract.
/// @param _token The erc20 token to grant.
/// @param _stale Stale block used for voting power calculations.
constructor(IERC20 _token, uint256 _stale)
AbstractVestingVault(_token, _stale)
{}
}
|
Update a delegatee's voting power. Voting power is only updated for this block onward. see `History` for more on how voting power is tracked and queried. Anybody can update a grant's voting power. _who the address who's voting power this function updates
|
function updateVotingPower(address _who) public {
VestingVaultStorage.Grant storage grant = _grants()[_who];
_syncVotingPower(_who, grant);
}
| 6,364,485 |
./partial_match/1/0x4A2be89f57846c7cdd66428017B2524D0b298518/sources/AcceptModifications.sol
|
/ Fetch withdrawal. Add accepted quantized amount. Store withdrawal. Log event. In ERC721 case, assetId is not the assetType.
|
function allowWithdrawal(
uint256 starkKey,
uint256 assetId,
uint256 quantizedAmount
)
internal
{
uint256 withdrawal = pendingWithdrawals[starkKey][assetId];
withdrawal += quantizedAmount;
require(withdrawal >= quantizedAmount, "WITHDRAWAL_OVERFLOW");
pendingWithdrawals[starkKey][assetId] = withdrawal;
uint256 presumedAssetType = assetId;
if (registeredAssetType[presumedAssetType]) {
emit LogWithdrawalAllowed(
starkKey,
presumedAssetType,
fromQuantized(presumedAssetType, quantizedAmount),
quantizedAmount
);
emit LogMintableWithdrawalAllowed(
starkKey,
assetId,
quantizedAmount
);
}
else {
require(withdrawal <= 1, "INVALID_NFT_AMOUNT");
emit LogNftWithdrawalAllowed(starkKey, assetId);
}
}
| 4,465,784 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
// Interface
import { ILazyMintERC1155 } from "./ILazyMintERC1155.sol";
// Token
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
// Protocol control center.
import { ProtocolControl } from "../../ProtocolControl.sol";
// Royalties
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
// Access Control + security
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
// Meta transactions
import "@openzeppelin/contracts/metatx/ERC2771Context.sol";
// Utils
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
// Helper interfaces
import { IWETH } from "../../interfaces/IWETH.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract LazyMintERC1155 is
ILazyMintERC1155,
ERC1155,
ERC2771Context,
IERC2981,
AccessControlEnumerable,
ReentrancyGuard,
Multicall
{
using Strings for uint256;
/// @dev Only TRANSFER_ROLE holders can have tokens transferred from or to them, during restricted transfers.
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev Only MINTER_ROLE holders can lazy mint NFTs (i.e. can call functions prefixed with `lazyMint`).
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @dev The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev The address of the native token wrapper contract.
address public immutable nativeTokenWrapper;
/// @dev The adress that receives all primary sales value.
address public defaultSaleRecipient;
/// @dev The next token ID of the NFT to "lazy mint".
uint256 public nextTokenIdToMint;
/// @dev Contract interprets 10_000 as 100%.
uint64 private constant MAX_BPS = 10_000;
/// @dev The % of secondary sales collected as royalties. See EIP 2981.
uint64 public royaltyBps;
/// @dev The % of primary sales collected by the contract as fees.
uint120 public feeBps;
/// @dev Whether transfers on tokens are restricted.
bool public transfersRestricted;
/// @dev Contract level metadata.
string public contractURI;
/// @dev The protocol control center.
ProtocolControl internal controlCenter;
uint256[] private baseURIIndices;
/// @dev End token Id => URI that overrides `baseURI + tokenId` convention.
mapping(uint256 => string) private baseURI;
/// @dev Token ID => total circulating supply of tokens with that ID.
mapping(uint256 => uint256) public totalSupply;
/// @dev Token ID => public claim conditions for tokens with that ID.
mapping(uint256 => ClaimConditions) public claimConditions;
/// @dev Token ID => the address of the recipient of primary sales.
mapping(uint256 => address) public saleRecipient;
/// @dev Checks whether caller has DEFAULT_ADMIN_ROLE on the protocol control center.
modifier onlyProtocolAdmin() {
require(controlCenter.hasRole(controlCenter.DEFAULT_ADMIN_ROLE(), _msgSender()), "not protocol admin.");
_;
}
/// @dev Checks whether caller has DEFAULT_ADMIN_ROLE.
modifier onlyModuleAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "not module admin.");
_;
}
/// @dev Checks whether caller has MINTER_ROLE.
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "not minter.");
_;
}
constructor(
string memory _contractURI,
address payable _controlCenter,
address _trustedForwarder,
address _nativeTokenWrapper,
address _saleRecipient,
uint128 _royaltyBps,
uint128 _feeBps
) ERC1155("") ERC2771Context(_trustedForwarder) {
controlCenter = ProtocolControl(_controlCenter);
nativeTokenWrapper = _nativeTokenWrapper;
defaultSaleRecipient = _saleRecipient;
contractURI = _contractURI;
royaltyBps = uint64(_royaltyBps);
feeBps = uint120(_feeBps);
address deployer = _msgSender();
_setupRole(DEFAULT_ADMIN_ROLE, deployer);
_setupRole(MINTER_ROLE, deployer);
_setupRole(TRANSFER_ROLE, deployer);
}
/// ===== Public functions =====
/// @dev Returns the URI for a given tokenId.
function uri(uint256 _tokenId) public view override returns (string memory _tokenURI) {
for (uint256 i = 0; i < baseURIIndices.length; i += 1) {
if (_tokenId < baseURIIndices[i]) {
return string(abi.encodePacked(baseURI[baseURIIndices[i]], _tokenId.toString()));
}
}
return "";
}
/// @dev Returns the URI for a given tokenId.
function tokenURI(uint256 _tokenId) public view returns (string memory _tokenURI) {
return uri(_tokenId);
}
/// @dev At any given moment, returns the uid for the active mint condition for a given tokenId.
function getIndexOfActiveCondition(uint256 _tokenId) public view returns (uint256) {
uint256 totalConditionCount = claimConditions[_tokenId].totalConditionCount;
require(totalConditionCount > 0, "no public mint condition.");
for (uint256 i = totalConditionCount; i > 0; i -= 1) {
if (block.timestamp >= claimConditions[_tokenId].claimConditionAtIndex[i - 1].startTimestamp) {
return i - 1;
}
}
revert("no active mint condition.");
}
/// ===== External functions =====
/**
* @dev Lets an account with `MINTER_ROLE` mint tokens of ID from `nextTokenIdToMint`
* to `nextTokenIdToMint + _amount - 1`. The URIs for these tokenIds is baseURI + `${tokenId}`.
*/
function lazyMint(uint256 _amount, string calldata _baseURIForTokens) external onlyMinter {
uint256 startId = nextTokenIdToMint;
uint256 baseURIIndex = startId + _amount;
nextTokenIdToMint = baseURIIndex;
baseURI[baseURIIndex] = _baseURIForTokens;
baseURIIndices.push(baseURIIndex);
emit LazyMintedTokens(startId, startId + _amount - 1, _baseURIForTokens);
}
/// @dev Lets an account claim a given quantity of tokens, of a single tokenId.
function claim(
uint256 _tokenId,
uint256 _quantity,
bytes32[] calldata _proofs
) external payable nonReentrant {
// Get the claim conditions.
uint256 activeConditionIndex = getIndexOfActiveCondition(_tokenId);
ClaimCondition memory condition = claimConditions[_tokenId].claimConditionAtIndex[activeConditionIndex];
// Verify claim validity. If not valid, revert.
verifyClaimIsValid(_tokenId, _quantity, _proofs, activeConditionIndex, condition);
// If there's a price, collect price.
collectClaimPrice(condition, _quantity, _tokenId);
// Mint the relevant tokens to claimer.
transferClaimedTokens(activeConditionIndex, _tokenId, _quantity);
emit ClaimedTokens(activeConditionIndex, _tokenId, _msgSender(), _quantity);
}
// @dev Lets a module admin update mint conditions without resetting the restrictions.
function updateClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions) external onlyModuleAdmin {
resetClaimConditions(_tokenId, _conditions);
emit NewClaimConditions(_tokenId, _conditions);
}
/// @dev Lets a module admin set mint conditions.
function setClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions) external onlyModuleAdmin {
uint256 numOfConditionsSet = resetClaimConditions(_tokenId, _conditions);
resetTimestampRestriction(_tokenId, numOfConditionsSet);
emit NewClaimConditions(_tokenId, _conditions);
}
/// @dev See EIP 2981
function royaltyInfo(uint256, uint256 salePrice)
external
view
virtual
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = controlCenter.getRoyaltyTreasury(address(this));
royaltyAmount = (salePrice * royaltyBps) / MAX_BPS;
}
// ===== Setter functions =====
/// @dev Lets a module admin set the default recipient of all primary sales.
function setDefaultSaleRecipient(address _saleRecipient) external onlyModuleAdmin {
defaultSaleRecipient = _saleRecipient;
emit NewSaleRecipient(_saleRecipient, type(uint256).max, true);
}
/// @dev Lets a module admin set the recipient of all primary sales for a given token ID.
function setSaleRecipient(uint256 _tokenId, address _saleRecipient) external onlyModuleAdmin {
saleRecipient[_tokenId] = _saleRecipient;
emit NewSaleRecipient(_saleRecipient, _tokenId, false);
}
/// @dev Lets a module admin update the royalties paid on secondary token sales.
function setRoyaltyBps(uint256 _royaltyBps) public onlyModuleAdmin {
require(_royaltyBps <= MAX_BPS, "bps <= 10000.");
royaltyBps = uint64(_royaltyBps);
emit RoyaltyUpdated(_royaltyBps);
}
/// @dev Lets a module admin update the fees on primary sales.
function setFeeBps(uint256 _feeBps) public onlyModuleAdmin {
require(_feeBps <= MAX_BPS, "bps <= 10000.");
feeBps = uint120(_feeBps);
emit PrimarySalesFeeUpdates(_feeBps);
}
/// @dev Lets a module admin restrict token transfers.
function setRestrictedTransfer(bool _restrictedTransfer) external onlyModuleAdmin {
transfersRestricted = _restrictedTransfer;
emit TransfersRestricted(_restrictedTransfer);
}
/// @dev Lets a module admin set the URI for contract-level metadata.
function setContractURI(string calldata _uri) external onlyProtocolAdmin {
contractURI = _uri;
}
// ===== Getter functions =====
/// @dev Returns the current active mint condition for a given tokenId.
function getTimestampForNextValidClaim(
uint256 _tokenId,
uint256 _index,
address _claimer
) public view returns (uint256 nextValidTimestampForClaim) {
uint256 timestampIndex = _index + claimConditions[_tokenId].timstampLimitIndex;
uint256 timestampOfLastClaim = claimConditions[_tokenId].timestampOfLastClaim[_claimer][timestampIndex];
unchecked {
nextValidTimestampForClaim =
timestampOfLastClaim +
claimConditions[_tokenId].claimConditionAtIndex[_index].waitTimeInSecondsBetweenClaims;
if (nextValidTimestampForClaim < timestampOfLastClaim) {
nextValidTimestampForClaim = type(uint256).max;
}
}
}
/// @dev Returns the mint condition for a given tokenId, at the given index.
function getClaimConditionAtIndex(uint256 _tokenId, uint256 _index)
external
view
returns (ClaimCondition memory mintCondition)
{
mintCondition = claimConditions[_tokenId].claimConditionAtIndex[_index];
}
// ===== Internal functions =====
/// @dev Lets a module admin set mint conditions for a given tokenId.
function resetClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions)
internal
returns (uint256 indexForCondition)
{
// make sure the conditions are sorted in ascending order
uint256 lastConditionStartTimestamp;
for (uint256 i = 0; i < _conditions.length; i++) {
require(
lastConditionStartTimestamp == 0 || lastConditionStartTimestamp < _conditions[i].startTimestamp,
"startTimestamp must be in ascending order."
);
require(_conditions[i].maxClaimableSupply > 0, "max mint supply cannot be 0.");
require(_conditions[i].quantityLimitPerTransaction > 0, "quantity limit cannot be 0.");
claimConditions[_tokenId].claimConditionAtIndex[indexForCondition] = ClaimCondition({
startTimestamp: _conditions[i].startTimestamp,
maxClaimableSupply: _conditions[i].maxClaimableSupply,
supplyClaimed: 0,
quantityLimitPerTransaction: _conditions[i].quantityLimitPerTransaction,
waitTimeInSecondsBetweenClaims: _conditions[i].waitTimeInSecondsBetweenClaims,
pricePerToken: _conditions[i].pricePerToken,
currency: _conditions[i].currency,
merkleRoot: _conditions[i].merkleRoot
});
indexForCondition += 1;
lastConditionStartTimestamp = _conditions[i].startTimestamp;
}
uint256 totalConditionCount = claimConditions[_tokenId].totalConditionCount;
if (indexForCondition < totalConditionCount) {
for (uint256 j = indexForCondition; j < totalConditionCount; j += 1) {
delete claimConditions[_tokenId].claimConditionAtIndex[j];
}
}
claimConditions[_tokenId].totalConditionCount = indexForCondition;
}
/// @dev Updates the `timstampLimitIndex` to reset the time restriction between claims, for a claim condition.
function resetTimestampRestriction(uint256 _tokenId, uint256 _factor) internal {
claimConditions[_tokenId].timstampLimitIndex += _factor;
}
/// @dev Checks whether a request to claim tokens obeys the active mint condition.
function verifyClaimIsValid(
uint256 _tokenId,
uint256 _quantity,
bytes32[] calldata _proofs,
uint256 _conditionIndex,
ClaimCondition memory _mintCondition
) internal view {
require(_quantity > 0 && _quantity <= _mintCondition.quantityLimitPerTransaction, "invalid quantity claimed.");
require(
_mintCondition.supplyClaimed + _quantity <= _mintCondition.maxClaimableSupply,
"exceed max mint supply."
);
uint256 timestampIndex = _conditionIndex + claimConditions[_tokenId].timstampLimitIndex;
uint256 timestampOfLastClaim = claimConditions[_tokenId].timestampOfLastClaim[_msgSender()][timestampIndex];
uint256 nextValidTimestampForClaim = getTimestampForNextValidClaim(_tokenId, _conditionIndex, _msgSender());
require(timestampOfLastClaim == 0 || block.timestamp >= nextValidTimestampForClaim, "cannot claim yet.");
if (_mintCondition.merkleRoot != bytes32(0)) {
bytes32 leaf = keccak256(abi.encodePacked(_msgSender()));
require(MerkleProof.verify(_proofs, _mintCondition.merkleRoot, leaf), "not in whitelist.");
}
}
/// @dev Collects and distributes the primary sale value of tokens being claimed.
function collectClaimPrice(
ClaimCondition memory _mintCondition,
uint256 _quantityToClaim,
uint256 _tokenId
) internal {
if (_mintCondition.pricePerToken <= 0) {
return;
}
uint256 totalPrice = _quantityToClaim * _mintCondition.pricePerToken;
uint256 fees = (totalPrice * feeBps) / MAX_BPS;
if (_mintCondition.currency == NATIVE_TOKEN) {
require(msg.value == totalPrice, "must send total price.");
} else {
validateERC20BalAndAllowance(_msgSender(), _mintCondition.currency, totalPrice);
}
transferCurrency(_mintCondition.currency, _msgSender(), controlCenter.getRoyaltyTreasury(address(this)), fees);
address recipient = saleRecipient[_tokenId];
transferCurrency(
_mintCondition.currency,
_msgSender(),
recipient == address(0) ? defaultSaleRecipient : recipient,
totalPrice - fees
);
}
/// @dev Transfers the tokens being claimed.
function transferClaimedTokens(
uint256 _claimConditionIndex,
uint256 _tokenId,
uint256 _quantityBeingClaimed
) internal {
// Update the supply minted under mint condition.
claimConditions[_tokenId].claimConditionAtIndex[_claimConditionIndex].supplyClaimed += _quantityBeingClaimed;
// Update the claimer's next valid timestamp to mint. If next mint timestamp overflows, cap it to max uint256.
uint256 timestampIndex = _claimConditionIndex + claimConditions[_tokenId].timstampLimitIndex;
claimConditions[_tokenId].timestampOfLastClaim[_msgSender()][timestampIndex] = block.timestamp;
_mint(_msgSender(), _tokenId, _quantityBeingClaimed, "");
}
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0 || _from == _to) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
IWETH(nativeTokenWrapper).withdraw(_amount);
safeTransferNativeToken(_to, _amount);
} else if (_to == address(this)) {
require(_amount == msg.value, "native token value does not match bid amount.");
IWETH(nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeToken(_to, _amount);
}
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Validates that `_addrToCheck` owns and has approved contract to transfer the appropriate amount of currency
function validateERC20BalAndAllowance(
address _addrToCheck,
address _currency,
uint256 _currencyAmountToCheckAgainst
) internal view {
require(
IERC20(_currency).balanceOf(_addrToCheck) >= _currencyAmountToCheckAgainst &&
IERC20(_currency).allowance(_addrToCheck, address(this)) >= _currencyAmountToCheckAgainst,
"insufficient currency balance or allowance."
);
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(nativeTokenWrapper).deposit{ value: value }();
safeTransferERC20(nativeTokenWrapper, address(this), to, value);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
uint256 balBefore = IERC20(_currency).balanceOf(_to);
bool success = IERC20(_currency).transferFrom(_from, _to, _amount);
uint256 balAfter = IERC20(_currency).balanceOf(_to);
require(success && balAfter == balBefore + _amount, "failed to transfer currency.");
}
/// ===== ERC 1155 functions =====
/// @dev Lets a token owner burn the tokens they own (i.e. destroy for good)
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved."
);
_burn(account, id, value);
}
/// @dev Lets a token owner burn multiple tokens they own at once (i.e. destroy for good)
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved."
);
_burnBatch(account, ids, values);
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
// if transfer is restricted on the contract, we still want to allow burning and minting
if (transfersRestricted && from != address(0) && to != address(0)) {
require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders.");
}
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
totalSupply[ids[i]] -= amounts[i];
}
}
}
/// ===== Low level overrides =====
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC1155, AccessControlEnumerable, IERC165)
returns (bool)
{
return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC2981).interfaceId;
}
function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) {
return ERC2771Context._msgSender();
}
function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {
return ERC2771Context._msgData();
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
/**
* `LazyMintERC1155` is an ERC 1155 contract. It takes in a base URI in its
* constructor (e.g. "ipsf://Qmece.../"), and the URI for each token of ID
* `tokenId` is baseURI + `${tokenId}` (e.g. "ipsf://Qmece.../1").
*
* For each token with a unique ID, the module admin (account with `DEFAULT_ADMIN ROLE`)
* can create mint conditions with non-overlapping time windows, and accounts can claim
* the NFTs, in a given time window, according to that time window's mint conditions.
*/
interface ILazyMintERC1155 {
/**
* @notice The mint conditions for a given tokenId x time window.
*
* @param startTimestamp The unix timestamp after which the mint conditions last.
* The same mint conditions last until the `startTimestamp`
* of the next mint condition.
*
* @param maxClaimableSupply The maximum number of tokens of the same `tokenId` that can
* be claimed under the mint condition.
*
* @param supplyClaimed At any given point, the number of tokens of the same `tokenId`
* that have been claimed.
*
* @param quantityLimitPerTransaction The maximum number of tokens a single account can
* claim in a single transaction.
*
* @param waitTimeInSecondsBetweenClaims The least number of seconds an account must wait
* after claiming tokens, to be able to claim again.
*
* @param merkleRoot Only accounts whose address is a leaf of `merkleRoot` can claim tokens
* under the mint condition.
*
* @param pricePerToken The price per token that can be claimed.
*
* @param currency The currency in which `pricePerToken` must be paid.
*/
struct ClaimCondition {
uint256 startTimestamp;
uint256 maxClaimableSupply;
uint256 supplyClaimed;
uint256 quantityLimitPerTransaction;
uint256 waitTimeInSecondsBetweenClaims;
bytes32 merkleRoot;
uint256 pricePerToken;
address currency;
}
/**
* @notice The set of all mint conditions for a given tokenId.
*
* @dev In the contract, we use this in a mapping: tokenId => mint conditions i.e.
* mapping(uint256 => PublicMintConditions) public mintConditions;
*
* @param totalConditionCount The uid for each mint condition. Incremented
* by one every time a mint condition is created.
*
* @param claimConditionAtIndex The mint conditions at a given uid. Mint conditions
* are ordered in an ascending order by their `startTimestamp`.
*
* @param nextValidTimestampForClaim Account => uid for a mint condition => timestamp after
* which the account can claim tokens again.
*/
struct ClaimConditions {
uint256 totalConditionCount;
uint256 timstampLimitIndex;
mapping(uint256 => ClaimCondition) claimConditionAtIndex;
mapping(address => mapping(uint256 => uint256)) timestampOfLastClaim;
}
/// @dev Emitted when tokens are lazy minted.
event LazyMintedTokens(uint256 startTokenId, uint256 endTokenId, string baseURI);
/// @dev Emitted when tokens are claimed.
event ClaimedTokens(
uint256 indexed claimConditionIndex,
uint256 indexed tokenId,
address indexed claimer,
uint256 quantityClaimed
);
/// @dev Emitted when new mint conditions are set for a token.
event NewClaimConditions(uint256 indexed tokenId, ClaimCondition[] claimConditions);
/// @dev Emitted when a new sale recipient is set.
event NewSaleRecipient(address indexed recipient, uint256 indexed _tokenId, bool isDefaultRecipient);
/// @dev Emitted when the royalty fee bps is updated
event RoyaltyUpdated(uint256 newRoyaltyBps);
/// @dev Emitted when fee on primary sales is updated.
event PrimarySalesFeeUpdates(uint256 newFeeBps);
/// @dev Emitted when transfers are set as restricted / not-restricted.
event TransfersRestricted(bool restricted);
/// @dev The next token ID of the NFT to "lazy mint".
function nextTokenIdToMint() external returns (uint256);
/**
* @notice Lets an account with `MINTER_ROLE` mint tokens of ID from `nextTokenIdToMint`
* to `nextTokenIdToMint + _amount - 1`. The URIs for these tokenIds is baseURI + `${tokenId}`.
*
* @param _amount The amount of tokens (each with a unique tokenId) to lazy mint.
*/
function lazyMint(uint256 _amount, string calldata _baseURIForTokens) external;
/**
* @notice Lets an account claim a given quantity of tokens, of a single tokenId.
*
* @param _tokenId The unique ID of the token to claim.
* @param _quantity The quantity of tokens to claim.
* @param _proofs The proof required to prove the account's inclusion in the merkle root whitelist
* of the mint conditions that apply.
*/
function claim(
uint256 _tokenId,
uint256 _quantity,
bytes32[] calldata _proofs
) external payable;
/**
* @notice Lets a module admin (account with `DEFAULT_ADMIN_ROLE`) set mint conditions for a given token ID.
*
* @param _tokenId The token ID for which to set mint conditions.
* @param _conditions Mint conditions in ascending order by `startTimestamp`.
*/
function setClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
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;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
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");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) 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 (uint256 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);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
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: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _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.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
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.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
// Access Control
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
// Registry
import { Registry } from "./Registry.sol";
import { Royalty } from "./Royalty.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract ProtocolControl is AccessControlEnumerable {
/// @dev MAX_BPS for the contract: 10_000 == 100%
uint128 public constant MAX_BPS = 10000;
/// @dev Module ID => Module address.
mapping(bytes32 => address) public modules;
/// @dev Module type => Num of modules of that type.
mapping(uint256 => uint256) public numOfModuleType;
/// @dev module address => royalty address
mapping(address => address) private moduleRoyalty;
/// @dev The top level app registry.
address public registry;
/// @dev Deployer's treasury
address public royaltyTreasury;
/// @dev The Forwarder for this app's modules.
address private _forwarder;
/// @dev Contract level metadata.
string private _contractURI;
/// @dev Events.
event ModuleUpdated(bytes32 indexed moduleId, address indexed module);
event TreasuryUpdated(address _newTreasury);
event ForwarderUpdated(address _newForwarder);
event FundsWithdrawn(address indexed to, address indexed currency, uint256 amount, uint256 fee);
event EtherReceived(address from, uint256 amount);
event RoyaltyTreasuryUpdated(
address indexed protocolControlAddress,
address indexed moduleAddress,
address treasury
);
/// @dev Check whether the caller is a protocol admin
modifier onlyProtocolAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"ProtocolControl: Only protocol admins can call this function."
);
_;
}
constructor(
address _registry,
address _admin,
string memory _uri
) {
// Set contract URI
_contractURI = _uri;
// Set top level ap registry
registry = _registry;
// Set default royalty treasury address
royaltyTreasury = address(this);
// Set access control roles
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
}
/// @dev Lets the contract receive ether.
receive() external payable {
emit EtherReceived(msg.sender, msg.value);
}
/// @dev Initialize treasury payment royalty splitting pool
function setRoyaltyTreasury(address payable _treasury) external onlyProtocolAdmin {
require(_isRoyaltyTreasuryValid(_treasury), "ProtocolControl: provider shares too low.");
royaltyTreasury = _treasury;
emit RoyaltyTreasuryUpdated(address(this), address(0), _treasury);
}
/// @dev _treasury must be PaymentSplitter compatible interface.
function setModuleRoyaltyTreasury(address moduleAddress, address payable _treasury) external onlyProtocolAdmin {
require(_isRoyaltyTreasuryValid(_treasury), "ProtocolControl: provider shares too low.");
moduleRoyalty[moduleAddress] = _treasury;
emit RoyaltyTreasuryUpdated(address(this), moduleAddress, _treasury);
}
/// @dev validate to make sure protocol provider (the registry) gets enough fees.
function _isRoyaltyTreasuryValid(address payable _treasury) private view returns (bool) {
// Get `Royalty` and `Registry` instances
Royalty royalty = Royalty(_treasury);
Registry _registry = Registry(registry);
// Calculate the protocol provider's shares.
uint256 royaltyRegistryShares = royalty.shares(_registry.treasury());
uint256 royaltyTotalShares = royalty.totalShares();
uint256 registryCutBps = (royaltyRegistryShares * MAX_BPS) / royaltyTotalShares;
// 10 bps (0.10%) tolerance in case of precision loss
// making sure registry treasury gets at least the fee's worth of shares.
uint256 feeBpsTolerance = 10;
return registryCutBps >= (_registry.getFeeBps(address(this)) - feeBpsTolerance);
}
/// @dev Returns the Royalty payment splitter for a particular module.
function getRoyaltyTreasury(address moduleAddress) external view returns (address) {
address moduleRoyaltyTreasury = moduleRoyalty[moduleAddress];
if (moduleRoyaltyTreasury == address(0)) {
return royaltyTreasury;
}
return moduleRoyaltyTreasury;
}
/// @dev Lets a protocol admin add a module to the protocol.
function addModule(address _newModuleAddress, uint256 _moduleType)
external
onlyProtocolAdmin
returns (bytes32 moduleId)
{
// `moduleId` is collision resitant -- unique `_moduleType` and incrementing `numOfModuleType`
moduleId = keccak256(abi.encodePacked(numOfModuleType[_moduleType], _moduleType));
numOfModuleType[_moduleType] += 1;
modules[moduleId] = _newModuleAddress;
emit ModuleUpdated(moduleId, _newModuleAddress);
}
/// @dev Lets a protocol admin change the address of a module of the protocol.
function updateModule(bytes32 _moduleId, address _newModuleAddress) external onlyProtocolAdmin {
require(modules[_moduleId] != address(0), "ProtocolControl: a module with this ID does not exist.");
modules[_moduleId] = _newModuleAddress;
emit ModuleUpdated(_moduleId, _newModuleAddress);
}
/// @dev Sets contract URI for the contract-level metadata of the contract.
function setContractURI(string calldata _URI) external onlyProtocolAdmin {
_contractURI = _URI;
}
/// @dev Lets the admin set a new Forwarder address [NOTE: for off-chain convenience only.]
function setForwarder(address forwarder) external onlyProtocolAdmin {
_forwarder = forwarder;
emit ForwarderUpdated(forwarder);
}
/// @dev Returns the URI for the contract-level metadata of the contract.
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @dev Returns all addresses for a module type
function getAllModulesOfType(uint256 _moduleType) external view returns (address[] memory allModules) {
uint256 numOfModules = numOfModuleType[_moduleType];
allModules = new address[](numOfModules);
for (uint256 i = 0; i < numOfModules; i += 1) {
bytes32 moduleId = keccak256(abi.encodePacked(i, _moduleType));
allModules[i] = modules[moduleId];
}
}
/// @dev Returns the forwarder address stored on the contract.
function getForwarder() public view returns (address) {
if (_forwarder == address(0)) {
return Registry(registry).forwarder();
}
return _forwarder;
}
function withdrawFunds(address to, address currency) external onlyProtocolAdmin {
Registry _registry = Registry(registry);
IERC20 _currency = IERC20(currency);
address registryTreasury = _registry.treasury();
uint256 registryTreasuryFee = 0;
uint256 amount = 0;
if (currency == address(0)) {
amount = address(this).balance;
} else {
amount = _currency.balanceOf(address(this));
}
registryTreasuryFee = (amount * _registry.getFeeBps(address(this))) / MAX_BPS;
amount = amount - registryTreasuryFee;
if (currency == address(0)) {
(bool sent, ) = payable(to).call{ value: amount }("");
require(sent, "failed to withdraw funds");
(bool sentRegistry, ) = payable(registryTreasury).call{ value: registryTreasuryFee }("");
require(sentRegistry, "failed to withdraw funds to registry");
emit FundsWithdrawn(to, currency, amount, registryTreasuryFee);
} else {
require(_currency.transferFrom(_msgSender(), to, amount), "failed to transfer payment");
require(
_currency.transferFrom(_msgSender(), registryTreasury, registryTreasuryFee),
"failed to transfer payment to registry"
);
emit FundsWithdrawn(to, currency, amount, registryTreasuryFee);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771Context is Context {
address private _trustedForwarder;
constructor(address trustedForwarder) {
_trustedForwarder = trustedForwarder;
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return forwarder == _trustedForwarder;
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./Address.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract Multicall {
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = Address.functionDelegateCall(address(this), data[i]);
}
return results;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
// CREATE2 -- contract deployment.
import "@openzeppelin/contracts/utils/Create2.sol";
// Access Control
import "@openzeppelin/contracts/access/Ownable.sol";
// Protocol Components
import { IControlDeployer } from "./interfaces/IControlDeployer.sol";
import { Forwarder } from "./Forwarder.sol";
import { ProtocolControl } from "./ProtocolControl.sol";
contract Registry is Ownable {
uint256 public constant MAX_PROVIDER_FEE_BPS = 1000; // 10%
uint256 public defaultFeeBps = 500; // 5%
/// @dev service provider / admin treasury
address public treasury;
/// @dev `Forwarder` for meta-transacitons
address public forwarder;
/// @dev The Create2 `ProtocolControl` contract factory.
IControlDeployer public deployer;
struct ProtocolControls {
// E.g. if `latestVersion == 2`, there are 2 `ProtocolControl` contracts deployed.
uint256 latestVersion;
// Mapping from version => contract address.
mapping(uint256 => address) protocolControlAddress;
}
/// @dev Mapping from app deployer => versions + app addresses.
mapping(address => ProtocolControls) private _protocolControls;
/// @dev Mapping from app (protocol control) => protocol provider fees for the app.
mapping(address => uint256) private protocolControlFeeBps;
/// @dev Emitted when the treasury is updated.
event TreasuryUpdated(address newTreasury);
/// @dev Emitted when a new deployer is set.
event DeployerUpdated(address newDeployer);
/// @dev Emitted when the default protocol provider fees bps is updated.
event DefaultFeeBpsUpdated(uint256 defaultFeeBps);
/// @dev Emitted when the protocol provider fees bps for a particular `ProtocolControl` is updated.
event ProtocolControlFeeBpsUpdated(address indexed control, uint256 feeBps);
/// @dev Emitted when an instance of `ProtocolControl` is migrated to this registry.
event MigratedProtocolControl(address indexed deployer, uint256 indexed version, address indexed controlAddress);
/// @dev Emitted when an instance of `ProtocolControl` is deployed.
event NewProtocolControl(
address indexed deployer,
uint256 indexed version,
address indexed controlAddress,
address controlDeployer
);
constructor(
address _treasury,
address _forwarder,
address _deployer
) {
treasury = _treasury;
forwarder = _forwarder;
deployer = IControlDeployer(_deployer);
}
/// @dev Deploys `ProtocolControl` with `_msgSender()` as admin.
function deployProtocol(string memory uri) external {
// Get deployer
address caller = _msgSender();
// Get version for deployment
uint256 version = getNextVersion(caller);
// Deploy contract and get deployment address.
address controlAddress = deployer.deployControl(version, caller, uri);
_protocolControls[caller].protocolControlAddress[version] = controlAddress;
emit NewProtocolControl(caller, version, controlAddress, address(deployer));
}
/// @dev Returns the latest version of protocol control.
function getProtocolControlCount(address _deployer) external view returns (uint256) {
return _protocolControls[_deployer].latestVersion;
}
/// @dev Returns the protocol control address for the given version.
function getProtocolControl(address _deployer, uint256 index) external view returns (address) {
return _protocolControls[_deployer].protocolControlAddress[index];
}
/// @dev Lets the owner migrate `ProtocolControl` instances from a previous registry.
function addProtocolControl(address _deployer, address _protocolControl) external onlyOwner {
// Get version for protocolControl
uint256 version = getNextVersion(_deployer);
_protocolControls[_deployer].protocolControlAddress[version] = _protocolControl;
emit MigratedProtocolControl(_deployer, version, _protocolControl);
}
/// @dev Sets a new `ProtocolControl` deployer in case `ProtocolControl` is upgraded.
function setDeployer(address _newDeployer) external onlyOwner {
deployer = IControlDeployer(_newDeployer);
emit DeployerUpdated(_newDeployer);
}
/// @dev Sets a new protocol provider treasury address.
function setTreasury(address _newTreasury) external onlyOwner {
treasury = _newTreasury;
emit TreasuryUpdated(_newTreasury);
}
/// @dev Sets a new `defaultFeeBps` for protocol provider fees.
function setDefaultFeeBps(uint256 _newFeeBps) external onlyOwner {
require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%");
defaultFeeBps = _newFeeBps;
emit DefaultFeeBpsUpdated(_newFeeBps);
}
/// @dev Sets the protocol provider fee for a particular instance of `ProtocolControl`.
function setProtocolControlFeeBps(address protocolControl, uint256 _newFeeBps) external onlyOwner {
require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%");
protocolControlFeeBps[protocolControl] = _newFeeBps;
emit ProtocolControlFeeBpsUpdated(protocolControl, _newFeeBps);
}
/// @dev Returns the protocol provider fee for a particular instance of `ProtocolControl`.
function getFeeBps(address protocolControl) external view returns (uint256) {
uint256 fees = protocolControlFeeBps[protocolControl];
if (fees == 0) {
return defaultFeeBps;
}
return fees;
}
/// @dev Returns the next version of `ProtocolControl` for the given `_deployer`.
function getNextVersion(address _deployer) internal returns (uint256) {
// Increment version
_protocolControls[_deployer].latestVersion += 1;
return _protocolControls[_deployer].latestVersion;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
// Base
import "./openzeppelin-presets/finance/PaymentSplitter.sol";
// Meta transactions
import "@openzeppelin/contracts/metatx/ERC2771Context.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import { Registry } from "./Registry.sol";
import { ProtocolControl } from "./ProtocolControl.sol";
/**
* Royalty automatically adds protocol provider (the registry) of protocol control to the payees
* and shares that represent the fees.
*/
contract Royalty is PaymentSplitter, AccessControlEnumerable, ERC2771Context, Multicall {
/// @dev The protocol control center.
ProtocolControl private controlCenter;
/// @dev Contract level metadata.
string private _contractURI;
modifier onlyModuleAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "only module admin role");
_;
}
/// @dev shares_ are scaled by 10,000 to prevent precision loss when including fees
constructor(
address payable _controlCenter,
address _trustedForwarder,
string memory _uri,
address[] memory payees,
uint256[] memory shares_
) PaymentSplitter() ERC2771Context(_trustedForwarder) {
require(payees.length == shares_.length, "Royalty: unequal number of payees and shares provided.");
require(payees.length > 0, "Royalty: no payees provided.");
// Set contract metadata
_contractURI = _uri;
// Set the protocol's control center.
controlCenter = ProtocolControl(_controlCenter);
Registry registry = Registry(controlCenter.registry());
uint256 feeBps = registry.getFeeBps(_controlCenter);
uint256 totalScaledShares = 0;
uint256 totalScaledSharesMinusFee = 0;
// Scaling the share, so we don't lose precision on division
for (uint256 i = 0; i < payees.length; i++) {
uint256 scaledShares = shares_[i] * 10000;
totalScaledShares += scaledShares;
uint256 feeFromScaledShares = (scaledShares * feeBps) / 10000;
uint256 scaledSharesMinusFee = scaledShares - feeFromScaledShares;
totalScaledSharesMinusFee += scaledSharesMinusFee;
// WARNING: Do not call _addPayee outside of this constructor.
_addPayee(payees[i], scaledSharesMinusFee);
}
// WARNING: Do not call _addPayee outside of this constructor.
uint256 totalFeeShares = totalScaledShares - totalScaledSharesMinusFee;
_addPayee(registry.treasury(), totalFeeShares);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/// @dev See ERC2771
function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) {
return ERC2771Context._msgSender();
}
/// @dev See ERC2771
function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {
return ERC2771Context._msgData();
}
/// @dev Sets contract URI for the contract-level metadata of the contract.
function setContractURI(string calldata _URI) external onlyModuleAdmin {
_contractURI = _URI;
}
/// @dev Returns the URI for the contract-level metadata of the contract.
function contractURI() public view returns (string memory) {
return _contractURI;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Create2.sol)
pragma solidity ^0.8.0;
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(
uint256 amount,
bytes32 salt,
bytes memory bytecode
) internal returns (address) {
address addr;
require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero");
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(
bytes32 salt,
bytes32 bytecodeHash,
address deployer
) internal pure returns (address) {
bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash));
return address(uint160(uint256(_data)));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
interface IControlDeployer {
/// @dev Emitted when an instance of `ProtocolControl` is deployed.
event DeployedControl(address indexed registry, address indexed deployer, address indexed control);
/// @dev Deploys an instance of `ProtocolControl`
function deployControl(
uint256 nonce,
address deployer,
string memory uri
) external returns (address);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
/*
* @dev Minimal forwarder for GSNv2
*/
contract Forwarder is EIP712 {
using ECDSA for bytes32;
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
bytes32 private constant TYPEHASH =
keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)");
mapping(address => uint256) private _nonces;
constructor() EIP712("GSNv2 Forwarder", "0.0.1") {}
function getNonce(address from) public view returns (uint256) {
return _nonces[from];
}
function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
address signer = _hashTypedDataV4(
keccak256(abi.encode(TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))
).recover(signature);
return _nonces[req.from] == req.nonce && signer == req.from;
}
function execute(ForwardRequest calldata req, bytes calldata signature)
public
payable
returns (bool, bytes memory)
{
require(verify(req, signature), "MinimalForwarder: signature does not match request");
_nonces[req.from] = req.nonce + 1;
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) = req.to.call{ gas: req.gas, value: req.value }(
abi.encodePacked(req.data, req.from)
);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert("Transaction reverted silently");
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
// Check gas: https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.gas / 63);
return (success, result);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* Changelog:
* 1. Remove add payees and shares in the constructor, so inherited class is responsible for adding.
* 2. Change _addPayee(...) visibility to internal. DANGEROUS: Make sure it is not called outside from constructor
* initialization.
* 3. Add distribute(...) to distribute all owed amount to all payees.
* 4. Add payeeCount() view to returns the number of payees.
*/
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor() payable {}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Getter for getting the number of payee
*/
function payeeCount() public view returns (uint256) {
return _payees.length;
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
* contract.
*/
function release(IERC20 token, address account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20Released[token][account] += payment;
_erc20TotalReleased[token] += payment;
SafeERC20.safeTransfer(token, account, payment);
emit ERC20PaymentReleased(token, account, payment);
}
/**
* @dev Release the owed amount of token to all of the payees.
*/
function distribute() public virtual {
for (uint256 i = 0; i < _payees.length; i++) {
release(payable(_payees[i]));
}
}
/**
* @dev Release owed amount of the `token` to all of the payees.
*/
function distribute(IERC20 token) public virtual {
for (uint256 i = 0; i < _payees.length; i++) {
release(token, _payees[i]);
}
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) internal {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
|
Transfer `amount` of ERC20 token from `from` to `to`.
|
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
uint256 balBefore = IERC20(_currency).balanceOf(_to);
bool success = IERC20(_currency).transferFrom(_from, _to, _amount);
uint256 balAfter = IERC20(_currency).balanceOf(_to);
require(success && balAfter == balBefore + _amount, "failed to transfer currency.");
}
| 12,651,405 |
./partial_match/4/0xcB4E1E9d824f73332a3D64F924E179d9846a36E8/sources/Lottery.sol
|
assert(msg.sender == governance.randomness());
|
function lotteryResult(uint256 randomness,uint256 _lotteryId) external {
require(randomness > 0, "random-not-found");
randomNumber[_lotteryId] = randomness;
address player = players[_lotteryId];
uint256 number = randomToReward(randomness);
numbers[_lotteryId] = number;
uint256 index = getOrder(number);
indexs[_lotteryId] = index;
require(NTFS.totalSupply(index) < NTFS.maxSupply(index), "Max cards minted");
NTFS.mint(player, index, 1, "");
emit NFTMint(player,index);
}
mapping (uint256 => uint256) public numbers;
mapping (uint256 => uint256) public indexs;
| 8,736,002 |
./full_match/5/0xB2832F76842bc6374Bf1997d50D4B39aBd01b966/sources/BTCpx.sol
|
Check if user is dao or not/
|
function isDAOUser(address _addr) public view returns(bool) {
return daoUsers[_addr].isDAO;
}
| 11,612,533 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IYieldGenerator.sol";
import "./interfaces/IDefiProtocol.sol";
import "./interfaces/ICapitalPool.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract YieldGenerator is IYieldGenerator, OwnableUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using Math for uint256;
uint256 public constant DEPOSIT_SAFETY_MARGIN = 15 * 10**24; //1.5
uint256 public constant PROTOCOLS_NUMBER = 3;
ERC20 public stblToken;
ICapitalPool public capitalPool;
uint256 public totalDeposit;
uint256 public whitelistedProtocols;
// index => defi protocol
mapping(uint256 => DefiProtocol) internal defiProtocols;
// index => defi protocol addresses
mapping(uint256 => address) public defiProtocolsAddresses;
// available protcols to deposit/withdraw (weighted and threshold is true)
uint256[] internal availableProtocols;
// selected protocols for multiple deposit/withdraw
uint256[] internal _selectedProtocols;
event DefiDeposited(
uint256 indexed protocolIndex,
uint256 amount,
uint256 depositedPercentage
);
event DefiWithdrawn(uint256 indexed protocolIndex, uint256 amount, uint256 withdrawPercentage);
modifier onlyCapitalPool() {
require(_msgSender() == address(capitalPool), "YG: Not a capital pool contract");
_;
}
modifier updateDefiProtocols(uint256 amount, bool isDeposit) {
_updateDefiProtocols(amount, isDeposit);
_;
}
function __YieldGenerator_init() external initializer {
__Ownable_init();
whitelistedProtocols = 3;
// setup AAVE
defiProtocols[uint256(DefiProtocols.AAVE)].targetAllocation = 45 * PRECISION;
defiProtocols[uint256(DefiProtocols.AAVE)].whiteListed = true;
defiProtocols[uint256(DefiProtocols.AAVE)].threshold = true;
// setup Compound
defiProtocols[uint256(DefiProtocols.COMPOUND)].targetAllocation = 45 * PRECISION;
defiProtocols[uint256(DefiProtocols.COMPOUND)].whiteListed = true;
defiProtocols[uint256(DefiProtocols.COMPOUND)].threshold = true;
// setup Yearn
defiProtocols[uint256(DefiProtocols.YEARN)].targetAllocation = 10 * PRECISION;
defiProtocols[uint256(DefiProtocols.YEARN)].whiteListed = true;
defiProtocols[uint256(DefiProtocols.YEARN)].threshold = true;
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
stblToken = ERC20(_contractsRegistry.getUSDTContract());
capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract());
defiProtocolsAddresses[uint256(DefiProtocols.AAVE)] = _contractsRegistry
.getAaveProtocolContract();
defiProtocolsAddresses[uint256(DefiProtocols.COMPOUND)] = _contractsRegistry
.getCompoundProtocolContract();
defiProtocolsAddresses[uint256(DefiProtocols.YEARN)] = _contractsRegistry
.getYearnProtocolContract();
}
/// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to deposit
function deposit(uint256 amount) external override onlyCapitalPool returns (uint256) {
if (amount == 0 && _getCurrentvSTBLVolume() == 0) return 0;
return _aggregateDepositWithdrawFunction(amount, true);
}
/// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to withdraw
function withdraw(uint256 amount) external override onlyCapitalPool returns (uint256) {
if (amount == 0 && _getCurrentvSTBLVolume() == 0) return 0;
return _aggregateDepositWithdrawFunction(amount, false);
}
/// @notice set the protocol settings for each defi protocol (allocations, whitelisted, depositCost), access: owner
/// @param whitelisted bool[] list of whitelisted values for each protocol
/// @param allocations uint256[] list of allocations value for each protocol
/// @param depositCost uint256[] list of depositCost values for each protocol
function setProtocolSettings(
bool[] calldata whitelisted,
uint256[] calldata allocations,
uint256[] calldata depositCost
) external override onlyOwner {
require(
whitelisted.length == PROTOCOLS_NUMBER &&
allocations.length == PROTOCOLS_NUMBER &&
depositCost.length == PROTOCOLS_NUMBER,
"YG: Invlaid arr length"
);
whitelistedProtocols = 0;
bool _whiteListed;
for (uint256 i = 0; i < PROTOCOLS_NUMBER; i++) {
_whiteListed = whitelisted[i];
if (_whiteListed) {
whitelistedProtocols = whitelistedProtocols.add(1);
}
defiProtocols[i].targetAllocation = allocations[i];
defiProtocols[i].whiteListed = _whiteListed;
defiProtocols[i].depositCost = depositCost[i];
}
}
/// @notice claim rewards for all defi protocols and send them to reinsurance pool, access: owner
function claimRewards() external override onlyOwner {
for (uint256 i = 0; i < PROTOCOLS_NUMBER; i++) {
IDefiProtocol(defiProtocolsAddresses[i]).claimRewards();
}
}
/// @notice returns defi protocol APR by its index
/// @param index uint256 the index of the defi protocol
function getOneDayGain(uint256 index) public view returns (uint256) {
return IDefiProtocol(defiProtocolsAddresses[index]).getOneDayGain();
}
/// @notice returns defi protocol info by its index
/// @param index uint256 the index of the defi protocol
function defiProtocol(uint256 index)
external
view
override
returns (
uint256 _targetAllocation,
uint256 _currentAllocation,
uint256 _rebalanceWeight,
uint256 _depositedAmount,
bool _whiteListed,
bool _threshold,
uint256 _totalValue,
uint256 _depositCost
)
{
_targetAllocation = defiProtocols[index].targetAllocation;
_currentAllocation = _calcProtocolCurrentAllocation(index);
_rebalanceWeight = defiProtocols[index].rebalanceWeight;
_depositedAmount = defiProtocols[index].depositedAmount;
_whiteListed = defiProtocols[index].whiteListed;
_threshold = defiProtocols[index].threshold;
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositCost = defiProtocols[index].depositCost;
}
function _aggregateDepositWithdrawFunction(uint256 amount, bool isDeposit)
internal
updateDefiProtocols(amount, isDeposit)
returns (uint256 _actualAmount)
{
if (availableProtocols.length == 0) {
return _actualAmount;
}
uint256 _protocolsNo = _howManyProtocols(amount, isDeposit);
if (_protocolsNo == 1) {
_actualAmount = _aggregateDepositWithdrawFunctionForOneProtocol(amount, isDeposit);
} else if (_protocolsNo > 1) {
delete _selectedProtocols;
uint256 _totalWeight = _calcTotalWeight(_protocolsNo, isDeposit);
if (_selectedProtocols.length > 0) {
for (uint256 i = 0; i < _selectedProtocols.length; i++) {
_actualAmount = _actualAmount.add(
_aggregateDepositWithdrawFunctionForMultipleProtocol(
isDeposit,
amount,
i,
_totalWeight
)
);
}
}
}
}
function _aggregateDepositWithdrawFunctionForOneProtocol(uint256 amount, bool isDeposit)
internal
returns (uint256 _actualAmount)
{
uint256 _protocolIndex;
if (isDeposit) {
_protocolIndex = _getProtocolOfMaxWeight();
// deposit 100% to this protocol
_depoist(_protocolIndex, amount, PERCENTAGE_100);
_actualAmount = amount;
} else {
_protocolIndex = _getProtocolOfMinWeight();
// withdraw 100% from this protocol
_actualAmount = _withdraw(_protocolIndex, amount, PERCENTAGE_100);
}
}
function _aggregateDepositWithdrawFunctionForMultipleProtocol(
bool isDeposit,
uint256 amount,
uint256 index,
uint256 _totalWeight
) internal returns (uint256 _actualAmount) {
uint256 _protocolRebalanceAllocation =
_calcRebalanceAllocation(_selectedProtocols[index], _totalWeight);
if (isDeposit) {
// deposit % allocation to this protocol
uint256 _depoistedAmount =
amount.mul(_protocolRebalanceAllocation).div(PERCENTAGE_100);
_depoist(_selectedProtocols[index], _depoistedAmount, _protocolRebalanceAllocation);
_actualAmount = _depoistedAmount;
} else {
_actualAmount = _withdraw(
_selectedProtocols[index],
amount.mul(_protocolRebalanceAllocation).div(PERCENTAGE_100),
_protocolRebalanceAllocation
);
}
}
function _calcTotalWeight(uint256 _protocolsNo, bool isDeposit)
internal
returns (uint256 _totalWeight)
{
uint256 _protocolIndex;
for (uint256 i = 0; i < _protocolsNo; i++) {
if (availableProtocols.length == 0) {
break;
}
if (isDeposit) {
_protocolIndex = _getProtocolOfMaxWeight();
} else {
_protocolIndex = _getProtocolOfMinWeight();
}
_totalWeight = _totalWeight.add(defiProtocols[_protocolIndex].rebalanceWeight);
_selectedProtocols.push(_protocolIndex);
}
}
/// @notice deposit into defi protocols
/// @param _protocolIndex uint256 the predefined index of the defi protocol
/// @param _amount uint256 amount of stable coin to deposit
/// @param _depositedPercentage uint256 the percentage of deposited amount into the protocol
function _depoist(
uint256 _protocolIndex,
uint256 _amount,
uint256 _depositedPercentage
) internal {
// should approve yield to transfer from the capital pool
stblToken.safeTransferFrom(_msgSender(), defiProtocolsAddresses[_protocolIndex], _amount);
IDefiProtocol(defiProtocolsAddresses[_protocolIndex]).deposit(_amount);
defiProtocols[_protocolIndex].depositedAmount = defiProtocols[_protocolIndex]
.depositedAmount
.add(_amount);
totalDeposit = totalDeposit.add(_amount);
emit DefiDeposited(_protocolIndex, _amount, _depositedPercentage);
}
/// @notice withdraw from defi protocols
/// @param _protocolIndex uint256 the predefined index of the defi protocol
/// @param _amount uint256 amount of stable coin to withdraw
/// @param _withdrawnPercentage uint256 the percentage of withdrawn amount from the protocol
function _withdraw(
uint256 _protocolIndex,
uint256 _amount,
uint256 _withdrawnPercentage
) internal returns (uint256) {
uint256 _actualAmountWithdrawn;
uint256 allocatedFunds = defiProtocols[_protocolIndex].depositedAmount;
if (allocatedFunds == 0) return _actualAmountWithdrawn;
if (allocatedFunds < _amount) {
_amount = allocatedFunds;
}
_actualAmountWithdrawn = IDefiProtocol(defiProtocolsAddresses[_protocolIndex]).withdraw(
_amount
);
defiProtocols[_protocolIndex].depositedAmount = defiProtocols[_protocolIndex]
.depositedAmount
.sub(_actualAmountWithdrawn);
totalDeposit = totalDeposit.sub(_actualAmountWithdrawn);
emit DefiWithdrawn(_protocolIndex, _actualAmountWithdrawn, _withdrawnPercentage);
return _actualAmountWithdrawn;
}
/// @notice get the number of protocols need to rebalance
/// @param rebalanceAmount uint256 the amount of stable coin will depsoit or withdraw
function _howManyProtocols(uint256 rebalanceAmount, bool isDeposit)
internal
view
returns (uint256)
{
uint256 _no1;
if (isDeposit) {
_no1 = whitelistedProtocols.mul(rebalanceAmount);
} else {
_no1 = PROTOCOLS_NUMBER.mul(rebalanceAmount);
}
uint256 _no2 = _getCurrentvSTBLVolume();
return _no1.add(_no2 - 1).div(_no2);
//return _no1.div(_no2).add(_no1.mod(_no2) == 0 ? 0 : 1);
}
/// @notice update defi protocols rebalance weight and threshold status
/// @param isDeposit bool determine the rebalance is for deposit or withdraw
function _updateDefiProtocols(uint256 amount, bool isDeposit) internal {
delete availableProtocols;
for (uint256 i = 0; i < PROTOCOLS_NUMBER; i++) {
uint256 _targetAllocation = defiProtocols[i].targetAllocation;
uint256 _currentAllocation = _calcProtocolCurrentAllocation(i);
uint256 _diffAllocation;
if (isDeposit) {
if (_targetAllocation > _currentAllocation) {
// max weight
_diffAllocation = _targetAllocation.sub(_currentAllocation);
} else if (_currentAllocation >= _targetAllocation) {
_diffAllocation = 0;
}
_reevaluateThreshold(i, _diffAllocation.mul(amount).div(PERCENTAGE_100));
} else {
if (_currentAllocation > _targetAllocation) {
// max weight
_diffAllocation = _currentAllocation.sub(_targetAllocation);
defiProtocols[i].withdrawMax = true;
} else if (_targetAllocation >= _currentAllocation) {
// min weight
_diffAllocation = _targetAllocation.sub(_currentAllocation);
defiProtocols[i].withdrawMax = false;
}
}
// update rebalance weight
defiProtocols[i].rebalanceWeight = _diffAllocation.mul(_getCurrentvSTBLVolume()).div(
PERCENTAGE_100
);
if (
isDeposit
? defiProtocols[i].rebalanceWeight > 0 &&
defiProtocols[i].whiteListed &&
defiProtocols[i].threshold
: _currentAllocation > 0
) {
availableProtocols.push(i);
}
}
}
/// @notice get the defi protocol has max weight to deposit
/// @dev only select the positive weight from largest to smallest
function _getProtocolOfMaxWeight() internal returns (uint256) {
uint256 _largest;
uint256 _protocolIndex;
uint256 _indexToDelete;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (defiProtocols[availableProtocols[i]].rebalanceWeight > _largest) {
_largest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_protocolIndex = availableProtocols[i];
_indexToDelete = i;
}
}
availableProtocols[_indexToDelete] = availableProtocols[availableProtocols.length - 1];
availableProtocols.pop();
return _protocolIndex;
}
/// @notice get the defi protocol has min weight to deposit
/// @dev only select the negative weight from smallest to largest
function _getProtocolOfMinWeight() internal returns (uint256) {
uint256 _maxWeight;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (defiProtocols[availableProtocols[i]].rebalanceWeight > _maxWeight) {
_maxWeight = defiProtocols[availableProtocols[i]].rebalanceWeight;
}
}
uint256 _smallest = _maxWeight;
uint256 _largest;
uint256 _maxProtocolIndex;
uint256 _maxIndexToDelete;
uint256 _minProtocolIndex;
uint256 _minIndexToDelete;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (
defiProtocols[availableProtocols[i]].rebalanceWeight <= _smallest &&
!defiProtocols[availableProtocols[i]].withdrawMax
) {
_smallest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_minProtocolIndex = availableProtocols[i];
_minIndexToDelete = i;
} else if (
defiProtocols[availableProtocols[i]].rebalanceWeight > _largest &&
defiProtocols[availableProtocols[i]].withdrawMax
) {
_largest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_maxProtocolIndex = availableProtocols[i];
_maxIndexToDelete = i;
}
}
if (_largest > 0) {
availableProtocols[_maxIndexToDelete] = availableProtocols[
availableProtocols.length - 1
];
availableProtocols.pop();
return _maxProtocolIndex;
} else {
availableProtocols[_minIndexToDelete] = availableProtocols[
availableProtocols.length - 1
];
availableProtocols.pop();
return _minProtocolIndex;
}
}
/// @notice calc the current allocation of defi protocol against current vstable volume
/// @param _protocolIndex uint256 the predefined index of defi protocol
function _calcProtocolCurrentAllocation(uint256 _protocolIndex)
internal
view
returns (uint256 _currentAllocation)
{
uint256 _depositedAmount = defiProtocols[_protocolIndex].depositedAmount;
uint256 _currentvSTBLVolume = _getCurrentvSTBLVolume();
if (_currentvSTBLVolume > 0) {
_currentAllocation = _depositedAmount.mul(PERCENTAGE_100).div(_currentvSTBLVolume);
}
}
/// @notice calc the rebelance allocation % for one protocol for deposit/withdraw
/// @param _protocolIndex uint256 the predefined index of defi protocol
/// @param _totalWeight uint256 sum of rebelance weight for all protocols which avaiable for deposit/withdraw
function _calcRebalanceAllocation(uint256 _protocolIndex, uint256 _totalWeight)
internal
view
returns (uint256)
{
return defiProtocols[_protocolIndex].rebalanceWeight.mul(PERCENTAGE_100).div(_totalWeight);
}
function _getCurrentvSTBLVolume() internal view returns (uint256) {
return
capitalPool.virtualUsdtAccumulatedBalance().sub(capitalPool.liquidityCushionBalance());
}
function _reevaluateThreshold(uint256 _protocolIndex, uint256 depositAmount) internal {
uint256 _protocolOneDayGain = getOneDayGain(_protocolIndex);
uint256 _oneDayReturn = _protocolOneDayGain.mul(depositAmount).div(PRECISION);
uint256 _depositCost = defiProtocols[_protocolIndex].depositCost;
if (_oneDayReturn < _depositCost) {
defiProtocols[_protocolIndex].threshold = false;
} else if (_oneDayReturn >= _depositCost) {
defiProtocols[_protocolIndex].threshold = true;
}
}
function reevaluateDefiProtocolBalances()
external
override
returns (uint256 _totalDeposit, uint256 _lostAmount)
{
_totalDeposit = totalDeposit;
uint256 _totalValue;
uint256 _depositedAmount;
for (uint256 index = 0; index < PROTOCOLS_NUMBER; index++) {
if (index == uint256(DefiProtocols.COMPOUND)) {
IDefiProtocol(defiProtocolsAddresses[index]).updateTotalValue();
}
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositedAmount = defiProtocols[index].depositedAmount;
if (_totalValue < _depositedAmount) {
_lostAmount = _lostAmount.add((_depositedAmount.sub(_totalValue)));
}
}
}
function defiHardRebalancing() external override onlyCapitalPool {
uint256 _totalValue;
uint256 _depositedAmount;
uint256 _lostAmount;
uint256 _totalLostAmount;
for (uint256 index = 0; index < PROTOCOLS_NUMBER; index++) {
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositedAmount = defiProtocols[index].depositedAmount;
if (_totalValue < _depositedAmount) {
_lostAmount = _depositedAmount.sub(_totalValue);
defiProtocols[index].depositedAmount = _depositedAmount.sub(_lostAmount);
IDefiProtocol(defiProtocolsAddresses[index]).updateTotalDeposit(_lostAmount);
_totalLostAmount = _totalLostAmount.add(_lostAmount);
}
}
totalDeposit = totalDeposit.sub(_lostAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFacade.sol";
interface ICapitalPool {
struct PremiumFactors {
uint256 epochsNumber;
uint256 premiumPrice;
uint256 vStblDeployedByRP;
uint256 vStblOfCP;
uint256 poolUtilizationRation;
uint256 premiumPerDeployment;
uint256 userLeveragePoolsCount;
IPolicyBookFacade policyBookFacade;
}
enum PoolType {COVERAGE, LEVERAGE, REINSURANCE}
function virtualUsdtAccumulatedBalance() external view returns (uint256);
function liquidityCushionBalance() external view returns (uint256);
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() external;
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external;
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
/// @param _isLeveragePool bool wether the pool is ULP or CP(policybook)
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
function rebalanceDuration() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityBridgeContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Interface for defi protocols (Compound, Aave, bZx, etc.)
interface IDefiProtocol {
/// @return uint256 The total value locked in the defi protocol, in terms of the underlying stablecoin
function totalValue() external view returns (uint256);
/// @return ERC20 the erc20 stable coin which depoisted in the defi protocol
function stablecoin() external view returns (ERC20);
/// @notice deposit an amount in defi protocol
/// @param amount uint256 the amount of stable coin will deposit
function deposit(uint256 amount) external;
/// @notice withdraw an amount from defi protocol
/// @param amountInUnderlying uint256 the amount of underlying token to withdraw the deposited stable coin
function withdraw(uint256 amountInUnderlying) external returns (uint256 actualAmountWithdrawn);
/// @notice Claims farmed tokens and sends it to the rewards pool
function claimRewards() external;
/// @notice set the address of receiving rewards
/// @param newValue address the new address to recieve the rewards
function setRewards(address newValue) external;
/// @notice get protocol gain for one day for one unit
function getOneDayGain() external view returns (uint256);
///@dev update total value only for compound
function updateTotalValue() external returns (uint256);
///@dev update total deposit in case of hard rebalancing
function updateTotalDeposit(uint256 _lostAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a1_ProtocolConstant uint256 A1 protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
function updateLiquidity(uint256 _lostLiquidity) external;
function forceUpdateBMICoverStakingRewardMultiplier() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external returns (uint256);
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
///@notice for doing defi hard rebalancing, access: policyBookFacade
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
address _insuranceContract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
function addLiquidityAndStakeFor(
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
///@dev in case ur changed of the pools by commit a claim or policy expired
function reevaluateProvidedLeverageStable() external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
function listUserLeveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _userLeveragePools);
function countUserLeveragePools() external view returns (uint256);
/// @notice get utilization rate of the pool on chain
function getUtilizationRatioPercentage(bool withLeverage) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IYieldGenerator {
enum DefiProtocols {AAVE, COMPOUND, YEARN}
struct DefiProtocol {
uint256 targetAllocation;
uint256 currentAllocation;
uint256 rebalanceWeight;
uint256 depositedAmount;
bool whiteListed;
bool threshold;
bool withdrawMax;
// new state post v2
uint256 totalValue;
uint256 depositCost;
}
/// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to deposit
function deposit(uint256 amount) external returns (uint256);
/// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to withdraw
function withdraw(uint256 amount) external returns (uint256);
/// @notice set the protocol settings for each defi protocol (allocations, whitelisted, depositCost), access: owner
/// @param whitelisted bool[] list of whitelisted values for each protocol
/// @param allocations uint256[] list of allocations value for each protocol
/// @param depositCost uint256[] list of depositCost values for each protocol
function setProtocolSettings(
bool[] calldata whitelisted,
uint256[] calldata allocations,
uint256[] calldata depositCost
) external;
/// @notice Claims farmed tokens and sends it to the reinsurance pool
function claimRewards() external;
/// @notice returns defi protocol info by its index
/// @param index uint256 the index of the defi protocol
function defiProtocol(uint256 index)
external
view
returns (
uint256 _targetAllocation,
uint256 _currentAllocation,
uint256 _rebalanceWeight,
uint256 _depositedAmount,
bool _whiteListed,
bool _threshold,
uint256 _totalValue,
uint256 _depositCost
);
function reevaluateDefiProtocolBalances()
external
returns (uint256 _totalDeposit, uint256 _lostAmount);
function defiHardRebalancing() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// 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: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
|
deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. leveragePoolType LeveragePortfolio is determine the pool which call the function deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner threshold uint256 is the reevaluatation threshold set the protocol constant : access by owner _targetUR uint256 target utitlization ration _d_ProtocolConstant uint256 D protocol constant _a1_ProtocolConstant uint256 A1 protocol constant _max_ProtocolConstant uint256 the max % included calc M factor by formual M = min( abs((1/ (Tur-UR))d) /a, max) poolUR uint256 utitilization ratio for a coverage pool return uint256 M facotrfunction calcM(uint256 poolUR) external returns (uint256); return uint256 the amount of vStable stored in the pool add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook epochsNumber uint256 the number of epochs which the policy holder will pay a premium for premiumAmount uint256 the premium amount which is a portion of 80% of the premium Used to get a list of coverage pools which get leveraged , use with count() return _coveragePools a list containing policybook addresses get count of coverage pools which get leveraged SPDX-License-Identifier: MIT
|
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
function deployVirtualStableToCoveragePools() external returns (uint256);
function setRebalancingThreshold(uint256 threshold) external;
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
function totalLiquidity() external view returns (uint256);
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
function countleveragedCoveragePools() external view returns (uint256);
function updateLiquidity(uint256 _lostLiquidity) external;
function forceUpdateBMICoverStakingRewardMultiplier() external;
}
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
}
| 9,888,594 |
./full_match/1/0xdf2D6F13C5F1556221028eE66545Ac2b7129F5bE/sources/browser/test.sol
|
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. solhint-disable-next-line no-inline-assembly
|
function isContract(address account) internal view returns (bool) {
uint size;
return size > 0;
}
| 9,665,025 |
pragma solidity ^0.4.17;
contract Projects {
address[16] public projectAdopters;
//joining a project
function joinProject(uint projectId) public returns (uint) {
require(projectId >= 0 && projectId <= 15);
projectAdopters[projectId] = msg.sender;
return projectId;
}
//getting potential projecting adopters
function getProjectAdopters() public view returns (address[16]) {
return projectAdopters;
}
}
|
getting potential projecting adopters
|
function getProjectAdopters() public view returns (address[16]) {
return projectAdopters;
}
| 7,274,688 |
./partial_match/1/0x7d755944D44Fc8b5183B82f55889B3FbE9bEbB8D/sources/PBull.sol
|
Set Transaction fee %, example, if 1% is the fee then set fee= 1000;
|
function setTransfee(uint256 _TransFee)
external
onlyOwner
{
Fee = _TransFee;
}
| 4,140,604 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./DividendPayingToken.sol";
import "./IterableMapping.sol";
contract HoneyBeeInuDividendTracker is DividendPayingToken {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public constant BASE = 10**18;
uint256 public lastProcessedIndex;
uint256 public claimWait;
uint256 public minimumTokenBalanceForDividends;
mapping (address => bool) public isExcludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
event ExcludeFromDividends(address indexed account, bool exclude);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount);
constructor() DividendPayingToken("Honey Bee Inu Dividends","HONEY_D"){
claimWait = 3600;
minimumTokenBalanceForDividends = 88_000_000 * BASE; //must buy at least 10M+ tokens to be eligibile for dividends
}
// view functions
function withdrawDividend() pure public override {
require(false, "disabled, use 'claim' function");
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address account) external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return _getAccount(account);
}
function _getAccount(address _account)
private view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return _getAccount(account);
}
// state functions
// // owner restricted
function excludeFromDividends(address account, bool exclude) external onlyOwner {
require(isExcludedFromDividends[account] != exclude,"already has been set!");
isExcludedFromDividends[account] = exclude;
uint256 bal = IERC20(owner()).balanceOf(account);
if(exclude){
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}else{
_setBalance(account, bal);
tokenHoldersMap.set(account, bal);
}
emit ExcludeFromDividends(account,exclude);
}
function updateMinimumForDividends(uint256 amount) external onlyOwner{
require((amount >= 1_000_000 * BASE) && // 1M minimum
(10_000_000_000 * BASE >= amount) // 10B maximum
,"should be 1M <= amount <= 10B");
require(amount != minimumTokenBalanceForDividends,"value already assigned!");
minimumTokenBalanceForDividends = amount;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 1800 && newClaimWait <= 86400, "must be updated 1 to 24 hours");
require(newClaimWait != claimWait, "same claimWait value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(isExcludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
_processAccount(account);
}
function processAccount(address payable account) external onlyOwner{
uint256 amount = _withdrawDividendOfUser(account);
emit Claim(account,amount);
}
function _processAccount(address payable account) private returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
return true;
}
return false;
}
// // public functions
function process(uint256 gas) external returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(_processAccount(payable(account))) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
// private
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
import "./SafeMathUint.sol";
import "./SafeMathInt.sol";
import "./IDividendPayingToken.sol";
import "./IDividendPayingTokenOptional.sol";
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is ERC20, IDividendPayingToken, IDividendPayingTokenOptional,Ownable {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
uint256 internal lastAmount;
uint256 public totalDividendsDistributed;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol){
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0,"dividened totalsupply error");
if (msg.value > 0) {
uint256 _magnifiedShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply());
magnifiedDividendPerShare = _magnifiedShare;
emit DividendsDistributed(msg.sender, msg.value);
uint256 _totalDistributed = totalDividendsDistributed.add(msg.value);
totalDividendsDistributed = _totalDistributed;
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
uint256 _withdrawnAmount = withdrawnDividends[user].add(_withdrawableDividend);
(bool success,) = user.call{value: _withdrawableDividend, gas:3000}("");
if(!success) {
return 0;
}
withdrawnDividends[user] = _withdrawnAmount;
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
uint256 _dividend = withdrawableDividendOf(_owner);
return _dividend;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
uint256 _withdrawable = accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
return _withdrawable;
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
uint256 _withdrawn = withdrawnDividends[_owner];
return _withdrawn;
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
uint256 _accumulative = magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
return _accumulative;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
function _transfer(address,address,uint256) internal virtual override {
require(false,"transfer inallowed");
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
int256 _correction = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
magnifiedDividendCorrections[account] = _correction;
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
int256 _correction = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
magnifiedDividendCorrections[account] = _correction;
}
function burn(uint256) external virtual override{
require(false,"burning unallowed");
}
/// @dev Internal function that adjusts an address dividends shares according to the new token balance.
/// @param account The account whose tokens will be proccessed .
/// @param newBalance The new address balance.
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./IERC20Metadata.sol";
import "./Context.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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from sender, 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(uint256 amount) external virtual{
_burn(msg.sender,amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT License
import "./Context.sol";
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0,"Negative number is not allowed");
return b;
}
}
// SPDX-License-Identifier: MIT
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity ^0.8.0;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256),"multplitiy error");
require((b == 0) || (c / b == a),"multiplity error mul");
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256,"SafeMath error div");
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a),"SafeMath error sub");
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a),"SafeMath error add");
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256,"SafeMath error abs");
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0,"SafeMath toUint error");
return uint256(a);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface IDividendPayingToken {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface IDividendPayingTokenOptional {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
Initializes the contract setting the deployer as the initial owner./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity ^0.8.0;
import "./Context.sol";
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
| 1,647,959 |
./full_match/42220/0xe6103ac30919ECb445FE23461CCC2bEBF315f54F/sources/contracts/community/CommunityAdminImplementation.sol
|
Removes an existing community. All community funds are transferred to the treasury _community address of the community/
|
function removeCommunity(ICommunity _community)
external
override
onlyOwnerOrImpactMarketCouncil
nonReentrant
{
require(
communities[address(_community)] == CommunityState.Valid,
"CommunityAdmin::removeCommunity: this isn't a valid community"
);
communities[address(_community)] = CommunityState.Removed;
ambassadors.removeCommunity(address(_community));
_community.transfer(cUSD, address(treasury), cUSD.balanceOf(address(_community)));
emit CommunityRemoved(address(_community));
}
| 16,348,048 |
pragma solidity ^0.4.18;
pragma solidity ^0.4.10;
/**
* @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;
}
}
contract owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 3;
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);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool);
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in 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);
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in 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 in 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] = balanceOf[msg.sender].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract MyAdvancedToken is owned, TokenERC20 {
uint256 public sellPrice = 2500 szabo; // 1 ETH=501$, 1,25$=1€=0,0025 ETH, 0,001ETH=1 finney=1000 szabo
uint256 public buyPrice = 2500 szabo; //
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transferadvanced(address _from, address _to, uint _value) internal returns (bool) {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
return true;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool) {
return _transferadvanced(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in 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] = allowance[_from][msg.sender].sub(_value);
return _transferadvanced(_from, _to, _value);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @dev fallback function ***DO NOT OVERRIDE***
function () external payable {
buy(msg.sender);
}
/// @notice Buy tokens from contract by sending ether
function buy(address _buyer) payable public {
uint amount = msg.value / (buyPrice / (10 ** uint(decimals))); // calculates the amount
_transferadvanced(this, _buyer, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount of tokens to be sold
function sell(uint256 amount) public {
uint value = amount * sellPrice / (10 ** uint(decimals)); //calculates value of tokens in ETH
require(address(this).balance >= value); // checks if the contract has enough ether to buy
_transferadvanced(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(value); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
}
|
Internal transfer, only can be called by this contract /
|
function _transferadvanced(address _from, address _to, uint _value) internal returns (bool) {
emit Transfer(_from, _to, _value);
return true;
}
| 10,178,697 |
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = getCTokenBalanceInternal(account);
uint borrowBalance = borrowBalanceStoredInternal(account);
uint exchangeRateMantissa = exchangeRateStoredInternal();
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the estimated per-block borrow interest rate for this cToken after some change
* @return The borrow interest rate per block, scaled by 1e18
*/
function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);
}
/**
* @notice Returns the estimated per-block supply interest rate for this cToken after some change
* @return The supply interest rate per block, scaled by 1e18
*/
function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
return borrowBalanceStoredInternal(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return the calculated balance or 0 if error code is non-zero
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint) {
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);
uint result = div_(principalTimesIndex, borrowSnapshot.interestIndex);
return result;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @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() public view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @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 exchangeRateStoredInternal() internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);
uint exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));
return exchangeRate;
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
uint blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior);
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta);
uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint totalBorrowsNew = add_(interestAccumulated, borrowsPrior);
uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @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
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount, bool isNative) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount, isNative);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens, bool isNative) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0, isNative);
}
/**
* @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 receive from redeeming cTokens
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount, bool isNative) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount, isNative);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount, bool isNative) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount, isNative);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount, bool isNative) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/*
* Return if borrowAmount is zero.
* Put behind `borrowAllowed` for accuring potential COMP rewards.
*/
if (borrowAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return uint(Error.NO_ERROR);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);
vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount, isNative);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount, bool isNative) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount, bool isNative) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount, bool isNative) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/*
* Return if repayAmount is zero.
* Put behind `repayBorrowAllowed` for accuring potential COMP rewards.
*/
if (repayAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return (uint(Error.NO_ERROR), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);
vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral, bool isNative) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral, bool isNative) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount, bool isNative) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount, isNative);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount, bool isNative) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount, isNative);
totalReservesNew = add_(totalReserves, actualAddAmount);
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = sub_(totalReserves, reduceAmount);
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// Restrict reducing reserves in native token. Implementations except `CWrappedNative` won't use parameter `isNative`.
doTransferOut(admin, reduceAmount, true);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount, bool isNative) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount, bool isNative) internal;
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint);
/**
* @notice Get the account's cToken balances
*/
function getCTokenBalanceInternal(address account) internal view returns (uint);
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
*/
function mintFresh(address minter, uint mintAmount, bool isNative) internal returns (uint, uint);
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn, bool isNative) internal returns (uint);
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint);
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CSupplyCapStorage {
/**
* @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20.
*/
uint256 public internalCash;
}
contract CCollateralCapStorage {
/**
* @notice Total number of tokens used as collateral in circulation.
*/
uint256 public totalCollateralTokens;
/**
* @notice Record of token balances which could be treated as collateral for each account.
* If collateral cap is not set, the value should be equal to accountTokens.
*/
mapping (address => uint) public accountCollateralTokens;
/**
* @notice Check if accountCollateralTokens have been initialized.
*/
mapping (address => bool) public isCollateralTokenInit;
/**
* @notice Collateral cap for this CToken, zero for no cap.
*/
uint256 public collateralCap;
}
/*** Interface ***/
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CWrappedNativeInterface is CErc20Interface {
/**
* @notice Flash loan fee ratio
*/
uint public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint amount, uint totalFee, uint reservesFee);
/*** User Interface ***/
function mintNative() external payable returns (uint);
function redeemNative(uint redeemTokens) external returns (uint);
function redeemUnderlyingNative(uint redeemAmount) external returns (uint);
function borrowNative(uint borrowAmount) external returns (uint);
function repayBorrowNative() external payable returns (uint);
function repayBorrowBehalfNative(address borrower) external payable returns (uint);
function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint);
function flashLoan(address payable receiver, uint amount, bytes calldata params) external;
/*** Admin Functions ***/
function _addReservesNative() external payable returns (uint);
}
contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage {
/**
* @notice Flash loan fee ratio
*/
uint public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint amount, uint totalFee, uint reservesFee);
/*** User Interface ***/
function gulp() external;
function flashLoan(address receiver, uint amount, bytes calldata params) external;
}
contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage {
/*** Admin Events ***/
/**
* @notice Event emitted when collateral cap is set
*/
event NewCollateralCap(address token, uint newCap);
/**
* @notice Event emitted when user collateral is changed
*/
event UserCollateralChanged(address account, uint newCollateralTokens);
/*** User Interface ***/
function registerCollateral(address account) external returns (uint);
function unregisterCollateral(address account) external;
/*** Admin Functions ***/
function _setCollateralCap(uint newCollateralCap) external;
}
contract CDelegatorInterface {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
/*** External interface ***/
/**
* @title Flash loan receiver interface
*/
interface IFlashloanReceiver {
function executeOperation(address sender, address underlying, uint amount, uint fee, bytes calldata params) external;
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";
import "./Governance/Comp.sol";
/**
* @title Compound's Comptroller Contract
* @author Compound (modified by Arr00)
*/
contract Comptroller is ComptrollerV6Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an admin delists a market
event MarketDelisted(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(CToken cToken, string action, bool pauseState);
/// @notice Emitted when COMP is distributed to a supplier
event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
/// @notice Emitted when COMP is distributed to a borrower
event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken indexed cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when supply cap for a cToken is changed
event NewSupplyCap(CToken indexed cToken, uint newSupplyCap);
/// @notice Emitted when supply cap guardian is changed
event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian);
/// @notice Emitted when cToken version is changed
event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion);
/// @notice The initial COMP index for a market
uint224 public constant compInitialIndex = 1e36;
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) public returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.version == Version.COLLATERALCAP) {
// register collateral for the borrower if the token is CollateralCap version.
CCollateralCapErc20Interface(address(cToken)).registerCollateral(borrower);
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[cTokenAddress];
if (marketToExit.version == Version.COLLATERALCAP) {
CCollateralCapErc20Interface(cTokenAddress).unregisterCollateral(msg.sender);
}
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
if (assetIndex != storedList.length - 1){
storedList[assetIndex] = storedList[storedList.length - 1];
}
storedList.length--;
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
uint supplyCap = supplyCaps[cToken];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint totalCash = CToken(cToken).getCash();
uint totalBorrows = CToken(cToken).totalBorrows();
uint totalReserves = CToken(cToken).totalReserves();
// totalSupplies = totalCash + totalBorrows - totalReserves
(MathError mathErr, uint totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
require(mathErr == MathError.NO_ERROR, "totalSupplies failed");
uint nextTotalSupplies = add_(totalSupplies, mintAmount);
require(nextTotalSupplies < supplyCap, "market supply cap reached");
}
distributeSupplierComp(cToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
distributeSupplierComp(cToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
distributeSupplierComp(cTokenCollateral, borrower);
distributeSupplierComp(cTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
distributeSupplierComp(cToken, src);
distributeSupplierComp(cToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param receiver The account which receives the tokens
* @param amount The amount of the tokens
* @param params The other parameters
*/
function flashloanAllowed(address cToken, address receiver, uint amount, bytes calldata params) external {
require(!flashloanGuardianPaused[cToken], "flashloan is paused");
// Shh - currently unused
receiver;
amount;
params;
}
/**
* @notice Update CToken's version.
* @param cToken Version of the asset being updated
* @param newVersion The new version
*/
function updateCTokenVersion(address cToken, Version newVersion) external {
require(msg.sender == cToken, "only cToken could update its version");
// This function will be called when a new CToken implementation becomes active.
// If a new CToken is newly created, this market is not listed yet. The version of
// this market will be taken care of when calling `_supportMarket`.
if (markets[cToken].isListed) {
Version oldVersion = markets[cToken].version;
markets[cToken].version = newVersion;
emit NewCTokenVersion(CToken(cToken), oldVersion, newVersion);
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * cTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
Exp memory numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
Exp memory ratio = div_(numerator, denominator);
uint seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param cToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param cToken The address of the market (token) to list
* @param version The version of the market (token)
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken, Version version) external returns (uint) {
require(msg.sender == admin, "only admin may support market");
require(!markets[address(cToken)].isListed, "market already listed");
cToken.isCToken(); // Sanity check to make sure its really a CToken
markets[address(cToken)] = Market({isListed: true, isComped: true, collateralFactorMantissa: 0, version: version});
_addMarketInternal(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
/**
* @notice Remove the market from the markets mapping
* @param cToken The address of the market (token) to delist
*/
function _delistMarket(CToken cToken) external {
require(msg.sender == admin, "only admin may delist market");
require(markets[address(cToken)].isListed, "market not listed");
require(cToken.totalSupply() == 0, "market not empty");
cToken.isCToken(); // Sanity check to make sure its really a CToken
delete markets[address(cToken)];
for (uint i = 0; i < allMarkets.length; i++) {
if (allMarkets[i] == cToken) {
allMarkets[i] = allMarkets[allMarkets.length - 1];
delete allMarkets[allMarkets.length - 1];
allMarkets.length--;
break;
}
}
emit MarketDelisted(cToken);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
/**
* @notice Admin function to change the Supply Cap Guardian
* @param newSupplyCapGuardian The address of the new Supply Cap Guardian
*/
function _setSupplyCapGuardian(address newSupplyCapGuardian) external {
require(msg.sender == admin, "only admin can set supply cap guardian");
// Save current value for inclusion in log
address oldSupplyCapGuardian = supplyCapGuardian;
// Store supplyCapGuardian with value newSupplyCapGuardian
supplyCapGuardian = newSupplyCapGuardian;
// Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian)
emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);
}
/**
* @notice Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert.
* @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows
* already exceeded the cap, it will prevent anyone to borrow.
* @param cTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(CToken[] calldata cTokens, uint[] calldata newSupplyCaps) external {
require(msg.sender == admin || msg.sender == supplyCapGuardian, "only admin or supply cap guardian can set supply caps");
uint numMarkets = cTokens.length;
uint numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
supplyCaps[address(cTokens[i])] = newSupplyCaps[i];
emit NewSupplyCap(cTokens[i], newSupplyCaps[i]);
}
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies
* already exceeded the cap, it will prevent anyone to mint.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setFlashloanPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
flashloanGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Flashloan", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/*** Comp Distribution ***/
/**
* @notice Calculate COMP accrued by a supplier and possibly transfer it to them
* @param cToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute COMP to
*/
function distributeSupplierComp(address cToken, address supplier) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]});
compSupplierIndex[cToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = transferComp(supplier, supplierAccrued);
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate COMP accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param cToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute COMP to
*/
function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]});
compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta);
compAccrued[borrower] = transferComp(borrower, borrowerAccrued);
emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer COMP to the user, if they are above the threshold
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param user The address of the user to transfer COMP to
* @param userAccrued The amount of COMP to (possibly) transfer
* @return The amount of COMP which was NOT transferred to the user
*/
function transferComp(address user, uint userAccrued) internal returns (uint) {
if (userAccrued > 0) {
Comp comp = Comp(getCompAddress());
uint compRemaining = comp.balanceOf(address(this));
if (userAccrued <= compRemaining) {
comp.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public {
address[] memory holders = new address[](1);
holders[0] = holder;
return claimComp(holders, allMarkets, true, true);
}
/**
* @notice Claim all comp accrued by the holders
* @param holders The addresses to claim COMP for
* @param cTokens The list of markets to claim COMP in
* @param borrowers Whether or not to claim COMP earned by borrowing
* @param suppliers Whether or not to claim COMP earned by supplying
*/
function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < cTokens.length; i++) {
CToken cToken = cTokens[i];
require(markets[address(cToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerComp(address(cToken), holders[j], borrowIndex);
}
}
if (suppliers == true) {
for (uint j = 0; j < holders.length; j++) {
distributeSupplierComp(address(cToken), holders[j]);
}
}
}
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the COMP token
* @return The address of COMP
*/
function getCompAddress() public view returns (address) {
return 0x2ba592F78dB6436527729929AAf6c908497cB200;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
import "./ComptrollerStorage.sol";
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
interface ComptrollerInterfaceExtension {
function checkMembership(address account, CToken cToken) external view returns (bool);
function updateCTokenVersion(address cToken, ComptrollerV2Storage.Version version) external;
function flashloanAllowed(address cToken, address receiver, uint amount, bytes calldata params) external;
}
pragma solidity ^0.5.16;
import "./CToken.sol";
import "./PriceOracle.sol";
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => CToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
enum Version {
VANILLA,
COLLATERALCAP
}
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives COMP
bool isComped;
/// @notice CToken version
Version version;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
struct CompMarketState {
/// @notice The market's last updated compBorrowIndex or compSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
CToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes COMP, per block
uint public compRate;
/// @notice The portion of compRate that each market currently receives
mapping(address => uint) public compSpeeds;
/// @notice The COMP market supply state for each market
mapping(address => CompMarketState) public compSupplyState;
/// @notice The COMP market borrow state for each market
mapping(address => CompMarketState) public compBorrowState;
/// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compSupplierIndex;
/// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compBorrowerIndex;
/// @notice The COMP accrued but not yet transferred to each user
mapping(address => uint) public compAccrued;
}
contract ComptrollerV4Storage is ComptrollerV3Storage {
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract ComptrollerV5Storage is ComptrollerV4Storage {
// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market.
address public supplyCapGuardian;
// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying.
mapping(address => uint) public supplyCaps;
}
contract ComptrollerV6Storage is ComptrollerV5Storage {
// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism.
mapping(address => bool) public flashloanGuardianPaused;
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_FRESHNESS_CHECK,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_FRESHNESS_CHECK,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function div_ScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint numerator = mul_(expScale, scalar);
return Exp({mantissa: div_(numerator, divisor)});
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function div_ScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) {
Exp memory fraction = div_ScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
// implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0
// original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint x) pure internal returns (uint) {
if (x == 0) return 0;
uint xx = x;
uint 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
uint r1 = x / r;
return (r < r1 ? r : r1);
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Cream";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "CREAM";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 9000000e18; // 9 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
import "./CToken.sol";
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external view returns (uint);
}
pragma solidity ^0.5.16;
import "./ErrorReporter.sol";
import "./ComptrollerStorage.sol";
/**
* @title ComptrollerCore
* @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`.
* CTokens should reference this contract as their comptroller.
*/
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
/**
* @notice Emitted when pendingComptrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
|
Admin function to change the Borrow Cap Guardian newBorrowCapGuardian The address of the new Borrow Cap Guardian/ Save current value for inclusion in log Store borrowCapGuardian with value newBorrowCapGuardian Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
|
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
address oldBorrowCapGuardian = borrowCapGuardian;
borrowCapGuardian = newBorrowCapGuardian;
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
| 263,604 |
./full_match/42/0x99743a2dF45bE75832c083e0d0644BF2E9F0a0C1/sources/contracts/mimic/SocialTraderToken.sol
|
Allows the social trader to make a trade on an active position with a predetermined strategy Allow trading of an active position with a predetermined strategy _timestamp UNIX value of when the position was opened _strategy string of the predetermined strategy
|
function executePredeterminedStrategy(uint256 _timestamp, bytes32 _strategy) external override onlyAdmin {
Position storage pos = positions[_timestamp];
_executeTradingOperation(strategies[_strategy], pos);
}
| 9,595,170 |
pragma solidity ^0.6.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @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;
}
function ceil(uint a, uint m) internal pure returns (uint r) {
return (a + m - 1) / m * m;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
abstract contract ERC20Interface {
function totalSupply() public virtual view returns (uint);
function balanceOf(address tokenOwner) public virtual view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public virtual returns (bool success);
function approve(address spender, uint256 tokens) public virtual returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
interface IERC20 {
function transfer(address to, uint256 tokens) external returns (bool success);
function transferFrom(address from, address to, uint256 tokens) external returns (bool success);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
// ----------------------------------------------------------------------------
// 'MCORE' token AND staking contract
// Symbol : MCORE
// Name : MetaCore
// Total supply: 7000 (7 thousands)
// Decimals : 18
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract MetaCore is ERC20Interface, Owned {
using SafeMath for uint256;
string public symbol = "MCORE";
string public name = "MetaCore";
uint256 public decimals = 18;
uint256 _totalSupply = 7e3 * 10 ** (decimals);
uint256 deployTime;
uint256 private totalDividentPoints;
uint256 pointMultiplier = 1000000000000000000;
uint256 public stakedCoins;
uint256 public totalRewardsClaimed;
address uniSwapAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address MCORE_WETH_POOL_ADDRESS = address(0);
address devs;
address communityFund;
struct Account {
uint256 balance;
uint256 lastDividentPoints;
uint256 timeInvest;
uint256 lastClaimed;
uint256 rewardsClaimed;
uint256 totalStakes;
uint256 pending;
}
mapping(address => Account) accounts;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
owner = 0xcC3d0B03DCC7C2d4f7C71E4DAFDb1C40A4829Df5;
devs = 0x81B794fad3BC654C8662614e83750E3541591fE5;
communityFund = 0x9F2742e7427E26DeC6beD359F0B4b5bff6A41bB3;
balances[communityFund] = totalSupply(); // 7000
emit Transfer(address(0), communityFund, totalSupply());
deployTime = block.timestamp;
}
function setLpsAddress(address _MCORE_WETH_POOL_ADDRESS) external onlyOwner{
require(_MCORE_WETH_POOL_ADDRESS != address(0), "Pool address cannot be zero");
require(MCORE_WETH_POOL_ADDRESS == address(0), "Pool address already set");
MCORE_WETH_POOL_ADDRESS = _MCORE_WETH_POOL_ADDRESS;
}
// ------------------------------------------------------------------------
// Stake the 'MCORE-WETH Lp' tokens to earn reward in 'MCORE'tokens
// ------------------------------------------------------------------------
function STAKE(uint256 _tokens) external returns(bool){
require(IERC20(MCORE_WETH_POOL_ADDRESS).transferFrom(msg.sender, address(this), _tokens), "Insufficient Tokens!");
stakedCoins = stakedCoins.add(_tokens); // MCORE_WETH Lp
uint256 owing = dividendsOwing(msg.sender); // MCORE tokens
if(owing > 0) { // checks previous pending rewards
accounts[msg.sender].pending = owing;
}
accounts[msg.sender].balance = accounts[msg.sender].balance.add(_tokens); // MCORE_WETH Lp
accounts[msg.sender].lastDividentPoints = totalDividentPoints; // MCORE tokens
accounts[msg.sender].timeInvest = now;
accounts[msg.sender].lastClaimed = now;
accounts[msg.sender].totalStakes = accounts[msg.sender].totalStakes.add(_tokens); // MCORE_WETH Lp
return true;
}
// ------------------------------------------------------------------------
// Gives the tokens in MCORE - ready to claim
// ------------------------------------------------------------------------
function pendingReward(address _user) external view returns(uint256 MCORE){
uint256 owing = dividendsOwing(_user);
return owing;
}
// ------------------------------------------------------------------------
// internal function used when MCORE tokens reward is claimed
// ------------------------------------------------------------------------
function updateDividend(address investor) internal returns(uint256){
uint256 owing = dividendsOwing(investor); // MCORE tokens
if (owing > 0){
accounts[investor].lastDividentPoints = totalDividentPoints;
}
return owing;
}
// ------------------------------------------------------------------------
// Gives the MCORE_WETH Lp tokens actively staked by the user
// ------------------------------------------------------------------------
function activeStake(address _user) external view returns (uint256){
return accounts[_user].balance;
}
// ------------------------------------------------------------------------
// Gives the MCORE_WETH Lp tokens staked by the user till the current date
// ------------------------------------------------------------------------
function totalStakesTillToday(address _user) external view returns (uint256){
return accounts[_user].totalStakes;
}
// ------------------------------------------------------------------------
// Used to stop the staking and get back MCORE_WETH Lp Tokens
// ------------------------------------------------------------------------
function UNSTAKE() external returns (bool){
require(stakedCoins > 0); // MCORE_WETH Lp
require(accounts[msg.sender].balance > 0); // MCORE_WETH Lp
uint256 owing = dividendsOwing(msg.sender); // MCORE tokens
if(owing > 0) { // checks previous pending rewards
accounts[msg.sender].pending = owing;
}
stakedCoins = stakedCoins.sub(accounts[msg.sender].balance); // MCORE_WETH Lp
require(IERC20(MCORE_WETH_POOL_ADDRESS).transfer(msg.sender, accounts[msg.sender].balance)); // sends the lp tokens back from the contract to the investor
accounts[msg.sender].balance = 0; // reset the balance of the investor
return true;
}
// -------------------------------------------------------------------------------
// Internal function used to disburse the MCORE tokens among all Lp tokens staked
// -------------------------------------------------------------------------------
function disburse(uint256 amount) internal{
uint256 unnormalized = amount.mul(pointMultiplier);
totalDividentPoints = totalDividentPoints.add(unnormalized.div(stakedCoins)); // stakedCoins is the MCORE_WETH lp tokens
}
// -------------------------------------------------------------------------------
// Internal function gives how much MCORE tokens reward is ready to be claimed
// -------------------------------------------------------------------------------
function dividendsOwing(address investor) internal view returns (uint256){
uint256 newDividendPoints = totalDividentPoints.sub(accounts[investor].lastDividentPoints);
return (((accounts[investor].balance).mul(newDividendPoints)).div(pointMultiplier)).add(accounts[investor].pending);
}
// -------------------------------------------------------------------------------
// Used to claim the reward in MCORE tokens
// -------------------------------------------------------------------------------
function claimReward() external returns(bool){
uint256 owing = updateDividend(msg.sender); // MCORE tokens ready to be claimed
require(_transfer(msg.sender, owing));
accounts[msg.sender].rewardsClaimed = accounts[msg.sender].rewardsClaimed.add(owing);
totalRewardsClaimed = totalRewardsClaimed.add(owing);
return true;
}
function rewardsClaimed(address _user) external view returns(uint256 rewardClaimed){
return accounts[_user].rewardsClaimed;
}
/** ERC20Interface function's implementation **/
function totalSupply() public override view returns (uint256){
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint256 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, uint256 tokens) public override returns (bool success) {
// prevent transfer to 0x0, use burn instead
require(address(to) != address(0));
require(balances[msg.sender] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
uint256 deduction = applyDeductions(to, tokens);
balances[to] = balances[to].add(tokens.sub(deduction));
emit Transfer(msg.sender, to, tokens.sub(deduction));
return true;
}
// ------------------------------------------------------------------------
// Apply 1.5% deduction on every token transfer
// 0.02% is given to the devs,
// 0.06% goes to a community fund,
// and the 1.42% goes to farmers split
// ------------------------------------------------------------------------
function applyDeductions(address to, uint256 tokens) private returns(uint256){
uint256 deduction = 0;
if(to != uniSwapAddress && to != address(this))
deduction = findOnePointFivePercent(tokens);
uint256 devsTokens = findZeroPointZeroTwoPercent(deduction);
balances[devs] = balances[devs].add(devsTokens);
emit Transfer(address(this), devs, devsTokens);
uint256 communityFundTokens = findZeroPointZeroSixPercent(deduction);
balances[communityFund] = balances[communityFund].add(communityFundTokens);
emit Transfer(address(this), communityFund, communityFundTokens);
if(stakedCoins == 0){
}
else{
balances[address(this)] = balances[address(this)].add(findOnePointFourTwoPercent(deduction));
disburse(findOnePointFourTwoPercent(deduction));
}
return deduction;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
// ------------------------------------------------------------------------
function approve(address spender, uint256 tokens) public override returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender,spender,tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){
require(tokens <= allowed[from][msg.sender]); //check allowance
require(balances[from] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
uint256 deduction = applyDeductions(to, tokens);
balances[to] = balances[to].add(tokens.sub(deduction));
emit Transfer(from, to, tokens.sub(tokens));
return true;
}
// no deductions are applied on claim of rewards
function _transfer(address to, uint256 tokens) internal returns(bool){
// prevent transfer to 0x0, use burn instead
require(address(to) != address(0));
require(balances[address(this)] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[address(this)] = balances[address(this)].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(address(this),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 override view returns (uint256 remaining) {
return allowed[tokenOwner][spender];
}
/***********************************************UTILITY FUNCTIONS**************************************************************************/
// ------------------------------------------------------------------------
// Calculates 1.5% of the value sent
// ------------------------------------------------------------------------
function findOnePointFivePercent(uint256 value) private pure returns (uint256) {
uint256 result = onePercent(value);
result = result.mul(15);
result = result.div(10);
return result;
}
// ------------------------------------------------------------------------
// Calculates 0.02% of the value sent
// ------------------------------------------------------------------------
function findZeroPointZeroTwoPercent(uint256 value) private pure returns (uint256) {
uint256 result = onePercent(value);
result = result.mul(2);
result = result.div(100);
return result;
}
// ------------------------------------------------------------------------
// Calculates 0.06% of the value sent
// ------------------------------------------------------------------------
function findZeroPointZeroSixPercent(uint256 value) private pure returns (uint256) {
uint256 result = onePercent(value);
result = result.mul(6);
result = result.div(100);
return result;
}
// ------------------------------------------------------------------------
// Calculates 1.42% of the value sent
// ------------------------------------------------------------------------
function findOnePointFourTwoPercent(uint256 value) private pure returns (uint256) {
uint256 result = onePercent(value);
result = result.mul(142);
result = result.div(100);
return result;
}
// ------------------------------------------------------------------------
// Calculates onePercent of the uint256 amount sent
// ------------------------------------------------------------------------
function onePercent(uint256 _tokens) internal pure returns (uint256){
uint256 roundValue = _tokens.ceil(100);
uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2));
return onePercentofTokens;
}
}
|
------------------------------------------------------------------------ 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, uint256 tokens) public override returns (bool success){
require(balances[from] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
uint256 deduction = applyDeductions(to, tokens);
balances[to] = balances[to].add(tokens.sub(deduction));
emit Transfer(from, to, tokens.sub(tokens));
return true;
}
| 6,046,651 |
/*
Copyright 2021 Babylon Finance
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
import {Address} from '@openzeppelin/contracts/utils/Address.sol';
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {AddressUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {IRewardsDistributor} from './interfaces/IRewardsDistributor.sol';
import {IGarden} from './interfaces/IGarden.sol';
import {IGardenFactory} from './interfaces/IGardenFactory.sol';
import {IStrategy} from './interfaces/IStrategy.sol';
import {IPriceOracle} from './interfaces/IPriceOracle.sol';
import {IIshtarGate} from './interfaces/IIshtarGate.sol';
import {IIntegration} from './interfaces/IIntegration.sol';
import {IBabController} from './interfaces/IBabController.sol';
import {IHypervisor} from './interfaces/IHypervisor.sol';
import {IWETH} from './interfaces/external/weth/IWETH.sol';
import {AddressArrayUtils} from './lib/AddressArrayUtils.sol';
import {LowGasSafeMath} from './lib/LowGasSafeMath.sol';
/**
* @title BabController
* @author Babylon Finance Protocol
*
* BabController is a smart contract used to deploy new gardens contracts and house the
* integrations and resources of the system.
*/
contract BabController is OwnableUpgradeable, IBabController {
using AddressArrayUtils for address[];
using Address for address;
using AddressUpgradeable for address;
using LowGasSafeMath for uint256;
using SafeERC20 for IERC20;
/* ============ Events ============ */
event GardenAdded(address indexed _garden, address indexed _factory);
event GardenRemoved(address indexed _garden);
event ControllerIntegrationAdded(address _integration, string indexed _integrationName);
event ControllerIntegrationRemoved(address _integration, string indexed _integrationName);
event ControllerIntegrationEdited(address _newIntegration, string indexed _integrationName);
event ControllerOperationSet(uint8 indexed _kind, address _address);
event MasterSwapperChanged(address indexed _newTradeIntegration, address _oldTradeIntegration);
event ReserveAssetAdded(address indexed _reserveAsset);
event ReserveAssetRemoved(address indexed _reserveAsset);
event LiquidityMinimumEdited(address indexed _resesrveAsset, uint256 _newMinLiquidityReserve);
event PriceOracleChanged(address indexed _priceOracle, address _oldPriceOracle);
event RewardsDistributorChanged(address indexed _rewardsDistributor, address _oldRewardsDistributor);
event TreasuryChanged(address _newTreasury, address _oldTreasury);
event IshtarGateChanged(address _newIshtarGate, address _oldIshtarGate);
event MardukGateChanged(address _newMardukGate, address _oldMardukGate);
event GardenValuerChanged(address indexed _gardenValuer, address _oldGardenValuer);
event GardenFactoryChanged(address indexed _gardenFactory, address _oldGardenFactory);
event UniswapFactoryChanged(address indexed _newUniswapFactory, address _oldUniswapFactory);
event GardenNFTChanged(address indexed _newGardenNFT, address _oldStrategyNFT);
event StrategyNFTChanged(address indexed _newStrategyNFT, address _oldStrategyNFT);
event HeartChanged(address indexed _newHeart, address _oldHeart);
event StrategyFactoryEdited(address indexed _strategyFactory, address _oldStrategyFactory);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address _oldPauseGuardian, address _newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string _action, bool _pauseState);
/// @notice Emitted when an action is paused individually
event ActionPausedIndividually(string _action, address _address, bool _pauseState);
/* ============ Modifiers ============ */
modifier onlyGovernanceOrEmergency {
require(msg.sender == owner() || msg.sender == EMERGENCY_OWNER, 'Not enough privileges');
_;
}
/* ============ State Variables ============ */
// List of enabled Communities
address[] public gardens;
address[] public reserveAssets;
address private uniswapFactory; // do not use
address public override gardenValuer;
address public override priceOracle;
address public override gardenFactory;
address public override rewardsDistributor;
address public override ishtarGate;
address public override strategyFactory;
address public override gardenNFT;
address public override strategyNFT;
// Mapping of integration name => integration address
mapping(bytes32 => address) private enabledIntegrations; // DEPRECATED
// Address of the master swapper used by the protocol
address public override masterSwapper;
// Mapping of valid operations
address[MAX_OPERATIONS] public override enabledOperations;
// Mappings to check whether address is valid Garden or Reserve Asset
mapping(address => bool) public override isGarden;
mapping(address => bool) public validReserveAsset;
// Mapping to check whitelisted assets
mapping(address => bool) public assetWhitelist;
// Mapping to check keepers
mapping(address => bool) public keeperList;
// Mapping of minimum liquidity per reserve asset
mapping(address => uint256) public override minLiquidityPerReserve;
// Recipient of protocol fees
address public override treasury;
// Strategy Profit Sharing
uint256 private strategistProfitPercentage; // DEPRECATED
uint256 private stewardsProfitPercentage; // DEPRECATED
uint256 private lpsProfitPercentage; // DEPRECATED
// Strategy BABL Rewards Sharing
uint256 private strategistBABLPercentage; // DEPRECATED
uint256 private stewardsBABLPercentage; // DEPRECATED
uint256 private lpsBABLPercentage; // DEPRECATED
uint256 private gardenCreatorBonus; // DEPRECATED
// Assets
// Enable Transfer of ERC20 gardenTokens
// Only members can transfer tokens until the protocol is fully decentralized
bool public override gardenTokensTransfersEnabled;
// Enable and starts the BABL Mining program within Rewards Distributor contract
bool public override bablMiningProgramEnabled;
// Enable public gardens
bool public override allowPublicGardens;
uint256 public override protocolPerformanceFee; // 5% (0.01% = 1e14, 1% = 1e16) on profits
uint256 public override protocolManagementFee; // 0.5% (0.01% = 1e14, 1% = 1e16)
uint256 private protocolDepositGardenTokenFee; // 0 (0.01% = 1e14, 1% = 1e16)
uint256 private protocolWithdrawalGardenTokenFee; // 0 (0.01% = 1e14, 1% = 1e16)
// Maximum number of contributors per garden
uint256 private maxContributorsPerGarden; // DEPRECATED
// Enable garden creations to be fully open to the public (no need of Ishtar gate anymore)
bool public override gardenCreationIsOpen;
// Pause Guardian
address public guardian;
mapping(address => bool) public override guardianPaused;
bool public override guardianGlobalPaused;
address public override mardukGate;
address public override heart;
/* ============ Constants ============ */
address public constant override EMERGENCY_OWNER = 0x0B892EbC6a4bF484CDDb7253c6BD5261490163b9;
IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 public constant BABL = IERC20(0xF4Dc48D260C93ad6a96c5Ce563E70CA578987c74);
uint8 public constant MAX_OPERATIONS = 20;
/* ============ Constructor ============ */
/**
* Initializes the initial fee recipient on deployment.
*/
function initialize() public initializer {
OwnableUpgradeable.__Ownable_init();
// vars init values has to be set in initialize due to how upgrade proxy pattern works
protocolManagementFee = 5e15; // 0.5% (0.01% = 1e14, 1% = 1e16)
protocolPerformanceFee = 5e16; // 5% (0.01% = 1e14, 1% = 1e16) on profits
protocolDepositGardenTokenFee = 0; // 0% (0.01% = 1e14, 1% = 1e16) on profits
protocolWithdrawalGardenTokenFee = 0; // 0% (0.01% = 1e14, 1% = 1e16) on profits
maxContributorsPerGarden = 100;
gardenCreationIsOpen = false;
allowPublicGardens = true;
bablMiningProgramEnabled = true;
}
/* ============ External Functions ============ */
// =========== Garden related Gov Functions ======
/**
* Creates a Garden smart contract and registers the Garden with the controller.
*
* If asset is not WETH, the creator needs to approve the controller
* @param _reserveAsset Reserve asset of the Garden. Initially just weth
* @param _name Name of the Garden
* @param _symbol Symbol of the Garden
* @param _gardenParams Array of numeric garden params
* @param _tokenURI Garden NFT token URI
* @param _seed Seed to regenerate the garden NFT
* @param _initialContribution Initial contribution by the gardener
* @param _publicGardenStrategistsStewards Public garden, public strategist rights and public stewards rights
* @param _profitSharing Custom profit sharing (if any)
*/
function createGarden(
address _reserveAsset,
string memory _name,
string memory _symbol,
string memory _tokenURI,
uint256 _seed,
uint256[] calldata _gardenParams,
uint256 _initialContribution,
bool[] memory _publicGardenStrategistsStewards,
uint256[] memory _profitSharing
) external payable override returns (address) {
require(masterSwapper != address(0), 'Need a default trade integration');
require(enabledOperations.length > 0, 'Need operations enabled');
require(
mardukGate != address(0) &&
gardenNFT != address(0) &&
strategyFactory != address(0) &&
gardenValuer != address(0) &&
treasury != address(0),
'Parameters not initialized'
);
require(
IIshtarGate(mardukGate).canCreate(msg.sender) || gardenCreationIsOpen,
'User does not have creation permissions'
);
address newGarden =
IGardenFactory(gardenFactory).createGarden(
_reserveAsset,
msg.sender,
_name,
_symbol,
_tokenURI,
_seed,
_gardenParams,
_initialContribution,
_publicGardenStrategistsStewards
);
if (_reserveAsset != address(WETH) || msg.value == 0) {
IERC20(_reserveAsset).safeTransferFrom(msg.sender, address(this), _initialContribution);
IERC20(_reserveAsset).safeApprove(newGarden, _initialContribution);
}
require(!isGarden[newGarden], 'Garden already exists');
isGarden[newGarden] = true;
gardens.push(newGarden);
IGarden(newGarden).deposit{value: msg.value}(_initialContribution, _initialContribution, msg.sender, true);
// Avoid gas cost if default sharing values are provided (0,0,0)
if (_profitSharing[0] != 0 || _profitSharing[1] != 0 || _profitSharing[2] != 0) {
IRewardsDistributor(rewardsDistributor).setProfitRewards(
newGarden,
_profitSharing[0],
_profitSharing[1],
_profitSharing[2]
);
}
emit GardenAdded(newGarden, msg.sender);
return newGarden;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a Garden
*
* @param _garden Address of the Garden contract to remove
*/
function removeGarden(address _garden) external override onlyOwner {
require(isGarden[_garden], 'Garden does not exist');
require(IGarden(_garden).getStrategies().length == 0, 'Garden has active strategies!');
gardens = gardens.remove(_garden);
delete isGarden[_garden];
emit GardenRemoved(_garden);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 gardenTokens
* Can only happen after 2021 is finished.
*/
function enableGardenTokensTransfers() external override onlyOwner {
require(block.timestamp > 1641024000, 'Transfers cannot be enabled yet');
gardenTokensTransfersEnabled = true;
}
// =========== Protocol related Gov Functions ======
/**
* PRIVILEGED FACTORY FUNCTION. Adds a new valid keeper to the list
*
* @param _keeper Address of the keeper
*/
function addKeeper(address _keeper) external override onlyOwner {
require(!keeperList[_keeper] && _keeper != address(0), 'Incorrect address');
keeperList[_keeper] = true;
}
/**
* PRIVILEGED FACTORY FUNCTION. Removes a keeper
*
* @param _keeper Address of the keeper
*/
function removeKeeper(address _keeper) external override onlyOwner {
require(keeperList[_keeper], 'Keeper is whitelisted');
delete keeperList[_keeper];
}
/**
* PRIVILEGED FACTORY FUNCTION. Adds a list of assets to the whitelist
*
* @param _keepers List with keeprs of the assets to whitelist
*/
function addKeepers(address[] memory _keepers) external override onlyOwner {
for (uint256 i = 0; i < _keepers.length; i++) {
keeperList[_keepers[i]] = true;
}
}
/**
* PRIVILEGED FACTORY FUNCTION. Adds a new valid reserve asset for gardens
*
* @param _reserveAsset Address of the reserve assset
*/
function addReserveAsset(address _reserveAsset) external override onlyOwner {
require(_reserveAsset != address(0) && ERC20(_reserveAsset).decimals() <= 18, 'Incorrect address');
require(!validReserveAsset[_reserveAsset], 'Reserve asset already added');
validReserveAsset[_reserveAsset] = true;
reserveAssets.push(_reserveAsset);
emit ReserveAssetAdded(_reserveAsset);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a reserve asset
*
* @param _reserveAsset Address of the reserve asset to remove
*/
function removeReserveAsset(address _reserveAsset) external override onlyOwner {
require(validReserveAsset[_reserveAsset], 'Reserve asset does not exist');
reserveAssets = reserveAssets.remove(_reserveAsset);
delete validReserveAsset[_reserveAsset];
emit ReserveAssetRemoved(_reserveAsset);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to change the Marduk Gate Address
*
* @param _mardukGate Address of the new Marduk Gate
*/
function editMardukGate(address _mardukGate) external override onlyOwner {
require(_mardukGate != mardukGate, 'Marduk Gate already exists');
require(_mardukGate != address(0), 'Marduk Gate oracle must exist');
address oldMardukGate = mardukGate;
mardukGate = _mardukGate;
emit MardukGateChanged(_mardukGate, oldMardukGate);
}
function editRewardsDistributor(address _newRewardsDistributor) external override onlyOwner {
require(_newRewardsDistributor != address(0), 'Address must not be 0');
address oldRewardsDistributor = rewardsDistributor;
rewardsDistributor = _newRewardsDistributor;
emit RewardsDistributorChanged(_newRewardsDistributor, oldRewardsDistributor);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol fee recipient
*
* @param _newTreasury Address of the new protocol fee recipient
*/
function editTreasury(address _newTreasury) external override onlyOwner {
require(_newTreasury != address(0), 'Address must not be 0');
address oldTreasury = treasury;
treasury = _newTreasury;
emit TreasuryChanged(_newTreasury, oldTreasury);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the heart contract
*
* @param _newHeart Address of the new heart
*/
function editHeart(address _newHeart) external override onlyGovernanceOrEmergency {
require(_newHeart != address(0), 'Address must not be 0');
address oldHeart = heart;
heart = _newHeart;
emit HeartChanged(_newHeart, oldHeart);
}
/**
* GOVERNANCE FUNCTION: Edits the minimum liquidity an asset must have on Uniswap
*
* @param _reserve Address of the reserve to edit
* @param _newMinLiquidityReserve Absolute min liquidity of an asset to grab price
*/
function editLiquidityReserve(address _reserve, uint256 _newMinLiquidityReserve) public override onlyOwner {
require(_newMinLiquidityReserve > 0, '_minRiskyPairLiquidityEth > 0');
require(validReserveAsset[_reserve], 'Needs to be a valid reserve');
minLiquidityPerReserve[_reserve] = _newMinLiquidityReserve;
emit LiquidityMinimumEdited(_reserve, _newMinLiquidityReserve);
}
// Setter that can be changed by the team in case of an emergency
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to change the price oracle
*
* @param _priceOracle Address of the new price oracle
*/
function editPriceOracle(address _priceOracle) external override onlyGovernanceOrEmergency {
require(_priceOracle != priceOracle, 'Price oracle already exists');
require(_priceOracle != address(0), 'Price oracle must exist');
address oldPriceOracle = priceOracle;
priceOracle = _priceOracle;
emit PriceOracleChanged(_priceOracle, oldPriceOracle);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to change the garden valuer
*
* @param _gardenValuer Address of the new garden valuer
*/
function editGardenValuer(address _gardenValuer) external override onlyGovernanceOrEmergency {
require(_gardenValuer != gardenValuer, 'Garden Valuer already exists');
require(_gardenValuer != address(0), 'Garden Valuer must exist');
address oldGardenValuer = gardenValuer;
gardenValuer = _gardenValuer;
emit GardenValuerChanged(_gardenValuer, oldGardenValuer);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol garden factory
*
* @param _newGardenFactory Address of the new garden factory
*/
function editGardenFactory(address _newGardenFactory) external override onlyGovernanceOrEmergency {
require(_newGardenFactory != address(0), 'Address must not be 0');
address oldGardenFactory = gardenFactory;
gardenFactory = _newGardenFactory;
emit GardenFactoryChanged(_newGardenFactory, oldGardenFactory);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol garden NFT
*
* @param _newGardenNFT Address of the new garden NFT
*/
function editGardenNFT(address _newGardenNFT) external override onlyGovernanceOrEmergency {
require(_newGardenNFT != address(0), 'Address must not be 0');
address oldGardenNFT = gardenNFT;
gardenNFT = _newGardenNFT;
emit GardenNFTChanged(_newGardenNFT, oldGardenNFT);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol strategy NFT
*
* @param _newStrategyNFT Address of the new strategy NFT
*/
function editStrategyNFT(address _newStrategyNFT) external override onlyGovernanceOrEmergency {
require(_newStrategyNFT != address(0), 'Address must not be 0');
address oldStrategyNFT = strategyNFT;
strategyNFT = _newStrategyNFT;
emit StrategyNFTChanged(_newStrategyNFT, oldStrategyNFT);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol strategy factory
*
* @param _newStrategyFactory Address of the new strategy factory
*/
function editStrategyFactory(address _newStrategyFactory) external override onlyGovernanceOrEmergency {
require(_newStrategyFactory != address(0), 'Address must not be 0');
address oldStrategyFactory = strategyFactory;
strategyFactory = _newStrategyFactory;
emit StrategyFactoryEdited(_newStrategyFactory, oldStrategyFactory);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol default trde integration
*
* @param _newDefaultMasterSwapper Address of the new default trade integration
*/
function setMasterSwapper(address _newDefaultMasterSwapper) external override onlyGovernanceOrEmergency {
require(_newDefaultMasterSwapper != address(0), 'Address must not be 0');
require(_newDefaultMasterSwapper != masterSwapper, 'Address must be different');
address oldMasterSwapper = masterSwapper;
masterSwapper = _newDefaultMasterSwapper;
emit MasterSwapperChanged(_newDefaultMasterSwapper, oldMasterSwapper);
}
/**
* GOVERNANCE FUNCTION: Edit an existing operation on the registry
*
* @param _kind Operation kind
* @param _operation Address of the operation contract to set
*/
function setOperation(uint8 _kind, address _operation) public override onlyGovernanceOrEmergency {
require(_kind < MAX_OPERATIONS, 'Max operations reached');
require(enabledOperations[_kind] != _operation, 'Operation already set');
require(_operation != address(0), 'Operation address must exist.');
enabledOperations[_kind] = _operation;
emit ControllerOperationSet(_kind, _operation);
}
// =========== Protocol security related Gov Functions ======
/**
* PRIVILEGED GOVERNANCE FUNCTION. Set-up a pause guardian
* @param _guardian Address of the guardian
*/
function setPauseGuardian(address _guardian) external override {
require(
msg.sender == guardian || msg.sender == owner(),
'only pause guardian and owner can update pause guardian'
);
require(msg.sender == owner() || _guardian != address(0), 'Guardian cannot remove himself');
// Save current value for inclusion in log
address oldPauseGuardian = guardian;
// Store pauseGuardian with value newPauseGuardian
guardian = _guardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, _guardian);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Pause the protocol globally in case of unexpected issue
* Only the governance can unpause it
* @param _state True to pause, false to unpause.
*/
function setGlobalPause(bool _state) external override returns (bool) {
require(msg.sender == guardian || msg.sender == owner(), 'only pause guardian and owner can pause globally');
require(msg.sender == owner() || _state == true, 'only admin can unpause');
guardianGlobalPaused = _state;
emit ActionPaused('Guardian global pause', _state);
return _state;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Pause some smartcontracts in a batch process in case of unexpected issue
* Only the governance can unpause it
* @param _address Addresses of protocol smartcontract to be paused
* @param _state Boolean pause state
*/
function setSomePause(address[] memory _address, bool _state) external override returns (bool) {
require(
msg.sender == guardian || msg.sender == owner(),
'only pause guardian and owner can pause individually'
);
require(msg.sender == owner() || _state == true, 'only admin can unpause');
for (uint256 i = 0; i < _address.length; i++) {
guardianPaused[_address[i]] = _state;
emit ActionPausedIndividually('Guardian individual pause', _address[i], _state);
}
return _state;
}
/* ============ External Getter Functions ============ */
function owner() public view override(IBabController, OwnableUpgradeable) returns (address) {
return OwnableUpgradeable.owner();
}
function getGardens() external view override returns (address[] memory) {
return gardens;
}
function getOperations() external view override returns (address[20] memory) {
return enabledOperations;
}
function getReserveAssets() external view override returns (address[] memory) {
return reserveAssets;
}
function isValidReserveAsset(address _reserveAsset) external view override returns (bool) {
return validReserveAsset[_reserveAsset];
}
function isValidKeeper(address _keeper) external view override returns (bool) {
return keeperList[_keeper];
}
/**
* Check whether or not there is a global pause or a specific pause of the provided contract address
* @param _contract Smartcontract address to check for a global or specific pause
*/
function isPaused(address _contract) external view override returns (bool) {
return guardianGlobalPaused || guardianPaused[_contract];
}
/**
* Check if a contract address is a garden or one of the system contracts
*
* @param _contractAddress The contract address to check
*/
function isSystemContract(address _contractAddress) external view override returns (bool) {
if (_contractAddress == address(0)) {
return false;
}
return (isGarden[_contractAddress] ||
gardenValuer == _contractAddress ||
priceOracle == _contractAddress ||
gardenFactory == _contractAddress ||
masterSwapper == _contractAddress ||
strategyFactory == _contractAddress ||
rewardsDistributor == _contractAddress ||
owner() == _contractAddress ||
_contractAddress == address(this) ||
_isOperation(_contractAddress) ||
(isGarden[address(IStrategy(_contractAddress).garden())] &&
IGarden(IStrategy(_contractAddress).garden()).strategyMapping(_contractAddress)) ||
(isGarden[address(IStrategy(_contractAddress).garden())] &&
IGarden(IStrategy(_contractAddress).garden()).isGardenStrategy(_contractAddress)));
}
/* ============ Internal Only Function ============ */
/**
* Hashes the string and returns a bytes32 value
*/
function _nameHash(string memory _name) private pure returns (bytes32) {
return keccak256(bytes(_name));
}
function _isOperation(address _address) private view returns (bool) {
for (uint8 i = 0; i < MAX_OPERATIONS; i++) {
if (_address == enabledOperations[i]) {
return true;
}
}
return false;
}
// Can receive ETH
// solhint-disable-next-line
receive() external payable {}
}
contract BabControllerV12 is BabController {}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/*
Copyright 2021 Babylon Finance.
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title IRewardsDistributor
* @author Babylon Finance
*
* Interface for the rewards distributor in charge of the BABL Mining Program.
*/
interface IRewardsDistributor {
/* ========== View functions ========== */
function getStrategyRewards(address _strategy) external view returns (uint256);
function getRewards(
address _garden,
address _contributor,
address[] calldata _finalizedStrategies
) external view returns (uint256[] memory);
function getGardenProfitsSharing(address _garden) external view returns (uint256[3] memory);
function checkMining(uint256 _quarterNum, address _strategy) external view returns (uint256[17] memory);
function estimateUserRewards(address _strategy, address _contributor) external view returns (uint256[] memory);
function estimateStrategyRewards(address _strategy) external view returns (uint256);
function getPriorBalance(
address _garden,
address _contributor,
uint256 _timestamp
)
external
view
returns (
uint256,
uint256,
uint256
);
/* ============ External Functions ============ */
function setProfitRewards(
address _garden,
uint256 _strategistShare,
uint256 _stewardsShare,
uint256 _lpShare
) external;
function migrateAddressToCheckpoints(address[] memory _garden, bool _toMigrate) external;
function setBABLMiningParameters(uint256[11] memory _newMiningParams) external;
function updateProtocolPrincipal(uint256 _capital, bool _addOrSubstract) external;
function updateGardenPowerAndContributor(
address _garden,
address _contributor,
uint256 _previousBalance,
uint256 _tokenDiff,
bool _addOrSubstract
) external;
function sendBABLToContributor(address _to, uint256 _babl) external returns (uint256);
}
/*
Copyright 2021 Babylon Finance
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title IGarden
* @author Babylon Finance
*
* Interface for operating with a Garden.
*/
interface IGarden {
/* ============ Functions ============ */
function initialize(
address _reserveAsset,
address _controller,
address _creator,
string memory _name,
string memory _symbol,
uint256[] calldata _gardenParams,
uint256 _initialContribution,
bool[] memory _publicGardenStrategistsStewards
) external payable;
function makeGardenPublic() external;
function transferCreatorRights(address _newCreator, uint8 _index) external;
function addExtraCreators(address[4] memory _newCreators) external;
function setPublicRights(bool _publicStrategist, bool _publicStewards) external;
function privateGarden() external view returns (bool);
function publicStrategists() external view returns (bool);
function publicStewards() external view returns (bool);
function controller() external view returns (address);
function creator() external view returns (address);
function isGardenStrategy(address _strategy) external view returns (bool);
function getContributor(address _contributor)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
);
function reserveAsset() external view returns (address);
function totalContributors() external view returns (uint256);
function gardenInitializedAt() external view returns (uint256);
function minContribution() external view returns (uint256);
function depositHardlock() external view returns (uint256);
function minLiquidityAsset() external view returns (uint256);
function minStrategyDuration() external view returns (uint256);
function maxStrategyDuration() external view returns (uint256);
function reserveAssetRewardsSetAside() external view returns (uint256);
function absoluteReturns() external view returns (int256);
function totalStake() external view returns (uint256);
function minVotesQuorum() external view returns (uint256);
function minVoters() external view returns (uint256);
function maxDepositLimit() external view returns (uint256);
function strategyCooldownPeriod() external view returns (uint256);
function getStrategies() external view returns (address[] memory);
function extraCreators(uint256 index) external view returns (address);
function getFinalizedStrategies() external view returns (address[] memory);
function strategyMapping(address _strategy) external view returns (bool);
function finalizeStrategy(
uint256 _profits,
int256 _returns,
uint256 _burningAmount
) external;
function allocateCapitalToStrategy(uint256 _capital) external;
function addStrategy(
string memory _name,
string memory _symbol,
uint256[] calldata _stratParams,
uint8[] calldata _opTypes,
address[] calldata _opIntegrations,
bytes calldata _opEncodedDatas
) external;
function deposit(
uint256 _reserveAssetQuantity,
uint256 _minGardenTokenReceiveQuantity,
address _to,
bool mintNFT
) external payable;
function depositBySig(
uint256 _amountIn,
uint256 _minAmountOut,
bool _mintNft,
uint256 _nonce,
uint256 _maxFee,
uint256 _pricePerShare,
uint256 _fee,
uint8 v,
bytes32 r,
bytes32 s
) external;
function withdraw(
uint256 _gardenTokenQuantity,
uint256 _minReserveReceiveQuantity,
address payable _to,
bool _withPenalty,
address _unwindStrategy
) external;
function withdrawBySig(
uint256 _gardenTokenQuantity,
uint256 _minReserveReceiveQuantity,
uint256 _nonce,
uint256 _maxFee,
bool _withPenalty,
address _unwindStrategy,
uint256 _pricePerShare,
uint256 _strategyNAV,
uint256 _fee,
uint8 v,
bytes32 r,
bytes32 s
) external;
function claimReturns(address[] calldata _finalizedStrategies) external;
function claimRewardsBySig(
uint256 _babl,
uint256 _profits,
uint256 _nonce,
uint256 _maxFee,
uint256 _fee,
uint8 v,
bytes32 r,
bytes32 s
) external;
function getLockedBalance(address _contributor) external view returns (uint256);
function updateGardenParams(uint256[9] memory _newParams) external;
function expireCandidateStrategy(address _strategy) external;
function payKeeper(address payable _keeper, uint256 _fee) external;
function keeperDebt() external view returns (uint256);
function totalKeeperFees() external view returns (uint256);
}
/*
Copyright 2021 Babylon Finance
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
import {IIntegration} from './IIntegration.sol';
/**
* @title IGardenFactory
* @author Babylon Finance
*
* Interface for the garden factory
*/
interface IGardenFactory {
function createGarden(
address _reserveAsset,
address _creator,
string memory _name,
string memory _symbol,
string memory _tokenURI,
uint256 _seed,
uint256[] calldata _gardenParams,
uint256 _initialContribution,
bool[] memory _publicGardenStrategistsStewards
) external returns (address);
}
/*
Copyright 2021 Babylon Finance
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
import {IGarden} from '../interfaces/IGarden.sol';
/**
* @title IStrategy
* @author Babylon Finance
*
* Interface for strategy
*/
interface IStrategy {
function initialize(
address _strategist,
address _garden,
address _controller,
uint256 _maxCapitalRequested,
uint256 _stake,
uint256 _strategyDuration,
uint256 _expectedReturn,
uint256 _maxAllocationPercentage,
uint256 _maxGasFeePercentage,
uint256 _maxTradeSlippagePercentage
) external;
function resolveVoting(
address[] calldata _voters,
int256[] calldata _votes,
uint256 fee
) external;
function updateParams(uint256[4] calldata _params) external;
function sweep(address _token, uint256 _newSlippage) external;
function setData(
uint8[] calldata _opTypes,
address[] calldata _opIntegrations,
bytes memory _opEncodedData
) external;
function executeStrategy(uint256 _capital, uint256 fee) external;
function getNAV() external view returns (uint256);
function opEncodedData() external view returns (bytes memory);
function getOperationsCount() external view returns (uint256);
function getOperationByIndex(uint8 _index)
external
view
returns (
uint8,
address,
bytes memory
);
function finalizeStrategy(
uint256 fee,
string memory _tokenURI,
uint256 _minReserveOut
) external;
function unwindStrategy(uint256 _amountToUnwind, uint256 _strategyNAV) external;
function invokeFromIntegration(
address _target,
uint256 _value,
bytes calldata _data
) external returns (bytes memory);
function invokeApprove(
address _spender,
address _asset,
uint256 _quantity
) external;
function trade(
address _sendToken,
uint256 _sendQuantity,
address _receiveToken
) external returns (uint256);
function handleWeth(bool _isDeposit, uint256 _wethAmount) external;
function getStrategyDetails()
external
view
returns (
address,
address,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256
);
function getStrategyState()
external
view
returns (
address,
bool,
bool,
bool,
uint256,
uint256,
uint256
);
function getStrategyRewardsContext()
external
view
returns (
address,
uint256[] memory,
bool[] memory
);
function isStrategyActive() external view returns (bool);
function getUserVotes(address _address) external view returns (int256);
function strategist() external view returns (address);
function enteredAt() external view returns (uint256);
function enteredCooldownAt() external view returns (uint256);
function stake() external view returns (uint256);
function strategyRewards() external view returns (uint256);
function maxCapitalRequested() external view returns (uint256);
function maxAllocationPercentage() external view returns (uint256);
function maxTradeSlippagePercentage() external view returns (uint256);
function maxGasFeePercentage() external view returns (uint256);
function expectedReturn() external view returns (uint256);
function duration() external view returns (uint256);
function totalPositiveVotes() external view returns (uint256);
function totalNegativeVotes() external view returns (uint256);
function capitalReturned() external view returns (uint256);
function capitalAllocated() external view returns (uint256);
function garden() external view returns (IGarden);
}
/*
Copyright 2021 Babylon Finance
Modified from (Set Protocol IPriceOracle)
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
import {ITokenIdentifier} from './ITokenIdentifier.sol';
/**
* @title IPriceOracle
* @author Babylon Finance
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function getPriceNAV(address _assetOne, address _assetTwo) external view returns (uint256);
function updateReserves(address[] memory list) external;
function updateMaxTwapDeviation(int24 _maxTwapDeviation) external;
function updateTokenIdentifier(ITokenIdentifier _tokenIdentifier) external;
function getCompoundExchangeRate(address _asset, address _finalAsset) external view returns (uint256);
function getCreamExchangeRate(address _asset, address _finalAsset) external view returns (uint256);
}
/*
Copyright 2021 Babylon Finance
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
import {IBabylonGate} from './IBabylonGate.sol';
/**
* @title IIshtarGate
* @author Babylon Finance
*
* Interface for interacting with the Gate Guestlist NFT
*/
interface IIshtarGate is IBabylonGate {
/* ============ Functions ============ */
function tokenURI() external view returns (string memory);
function updateGardenURI(string memory _tokenURI) external;
}
/*
Copyright 2021 Babylon Finance
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title IIntegration
* @author Babylon Finance
*
* Interface for protocol integrations
*/
interface IIntegration {
function getName() external view returns (string memory);
}
/*
Copyright 2021 Babylon Finance.
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title IBabController
* @author Babylon Finance
*
* Interface for interacting with BabController
*/
interface IBabController {
/* ============ Functions ============ */
function createGarden(
address _reserveAsset,
string memory _name,
string memory _symbol,
string memory _tokenURI,
uint256 _seed,
uint256[] calldata _gardenParams,
uint256 _initialContribution,
bool[] memory _publicGardenStrategistsStewards,
uint256[] memory _profitSharing
) external payable returns (address);
function removeGarden(address _garden) external;
function addReserveAsset(address _reserveAsset) external;
function removeReserveAsset(address _reserveAsset) external;
function editPriceOracle(address _priceOracle) external;
function editMardukGate(address _mardukGate) external;
function editGardenValuer(address _gardenValuer) external;
function editTreasury(address _newTreasury) external;
function editHeart(address _newHeart) external;
function editRewardsDistributor(address _rewardsDistributor) external;
function editGardenFactory(address _newGardenFactory) external;
function editGardenNFT(address _newGardenNFT) external;
function editStrategyNFT(address _newStrategyNFT) external;
function editStrategyFactory(address _newStrategyFactory) external;
function setOperation(uint8 _kind, address _operation) external;
function setMasterSwapper(address _newMasterSwapper) external;
function addKeeper(address _keeper) external;
function addKeepers(address[] memory _keepers) external;
function removeKeeper(address _keeper) external;
function enableGardenTokensTransfers() external;
function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external;
function gardenCreationIsOpen() external view returns (bool);
function owner() external view returns (address);
function EMERGENCY_OWNER() external view returns (address);
function guardianGlobalPaused() external view returns (bool);
function guardianPaused(address _address) external view returns (bool);
function setPauseGuardian(address _guardian) external;
function setGlobalPause(bool _state) external returns (bool);
function setSomePause(address[] memory _address, bool _state) external returns (bool);
function isPaused(address _contract) external view returns (bool);
function priceOracle() external view returns (address);
function gardenValuer() external view returns (address);
function heart() external view returns (address);
function gardenNFT() external view returns (address);
function strategyNFT() external view returns (address);
function rewardsDistributor() external view returns (address);
function gardenFactory() external view returns (address);
function treasury() external view returns (address);
function ishtarGate() external view returns (address);
function mardukGate() external view returns (address);
function strategyFactory() external view returns (address);
function masterSwapper() external view returns (address);
function gardenTokensTransfersEnabled() external view returns (bool);
function bablMiningProgramEnabled() external view returns (bool);
function allowPublicGardens() external view returns (bool);
function enabledOperations(uint256 _kind) external view returns (address);
function getGardens() external view returns (address[] memory);
function getReserveAssets() external view returns (address[] memory);
function getOperations() external view returns (address[20] memory);
function isGarden(address _garden) external view returns (bool);
function isValidReserveAsset(address _reserveAsset) external view returns (bool);
function isValidKeeper(address _keeper) external view returns (bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function protocolPerformanceFee() external view returns (uint256);
function protocolManagementFee() external view returns (uint256);
function minLiquidityPerReserve(address _reserve) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IHypervisor {
// @param deposit0 Amount of token0 transfered from sender to Hypervisor
// @param deposit1 Amount of token0 transfered from sender to Hypervisor
// @param to Address to which liquidity tokens are minted
// @return shares Quantity of liquidity tokens minted as a result of deposit
function deposit(
uint256 deposit0,
uint256 deposit1,
address to
) external returns (uint256);
// @param shares Number of liquidity tokens to redeem as pool assets
// @param to Address to which redeemed pool assets are sent
// @param from Address from which liquidity tokens are sent
// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
function withdraw(
uint256 shares,
address to,
address from
) external returns (uint256, uint256);
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address _feeRecipient,
int256 swapQuantity
) external;
function addBaseLiquidity(uint256 amount0, uint256 amount1) external;
function addLimitLiquidity(uint256 amount0, uint256 amount1) external;
function pullLiquidity(uint256 shares)
external
returns (
uint256 base0,
uint256 base1,
uint256 limit0,
uint256 limit1
);
function token0() external view returns (IERC20);
function token1() external view returns (IERC20);
function balanceOf(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function transferFrom(
address,
address,
uint256
) external returns (bool);
function transfer(address, uint256) external returns (bool);
function getTotalAmounts() external view returns (uint256 total0, uint256 total1);
function pendingFees() external returns (uint256 fees0, uint256 fees1);
function totalSupply() external view returns (uint256);
function setMaxTotalSupply(uint256 _maxTotalSupply) external;
function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external;
function appendList(address[] memory listed) external;
function toggleWhitelist() external;
function transferOwnership(address newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/*
Unfortunately Solidity does not support convertion of the fixed array to dynamic array so these functions are
required. This functionality would be supported in the future so these methods can be removed.
*/
function toDynamic(address _one, address _two) internal pure returns (address[] memory) {
address[] memory arr = new address[](2);
arr[0] = _one;
arr[1] = _two;
return arr;
}
function toDynamic(
address _one,
address _two,
address _three
) internal pure returns (address[] memory) {
address[] memory arr = new address[](3);
arr[0] = _one;
arr[1] = _two;
arr[2] = _three;
return arr;
}
function toDynamic(
address _one,
address _two,
address _three,
address _four
) internal pure returns (address[] memory) {
address[] memory arr = new address[](4);
arr[0] = _one;
arr[1] = _two;
arr[2] = _three;
arr[3] = _four;
return arr;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/*
Copyright 2021 Babylon Finance
Modified from (Set Protocol IPriceOracle)
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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title IPriceOracle
* @author Babylon Finance
*
* Interface for interacting with PriceOracle
*/
interface ITokenIdentifier {
/* ============ Functions ============ */
function identifyTokens(address _tokenIn, address _tokenOut)
external
view
returns (
uint8,
uint8,
address,
address
);
function updateYearnVault(address[] calldata _vaults, bool[] calldata _values) external;
function updateSynth(address[] calldata _synths, bool[] calldata _values) external;
function updateCreamPair(address[] calldata _creamTokens, address[] calldata _underlyings) external;
function updateAavePair(address[] calldata _aaveTokens, address[] calldata _underlyings) external;
function updateCompoundPair(address[] calldata _cTokens, address[] calldata _underlyings) external;
}
/*
Copyright 2021 Babylon Finance
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
distributedx 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.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.7.6;
/**
* @title IBabylonGate
* @author Babylon Finance
*
* Interface for interacting with the Guestlists
*/
interface IBabylonGate {
/* ============ Functions ============ */
function setGardenAccess(
address _user,
address _garden,
uint8 _permission
) external returns (uint256);
function setCreatorPermissions(address _user, bool _canCreate) external returns (uint256);
function grantGardenAccessBatch(
address _garden,
address[] calldata _users,
uint8[] calldata _perms
) external returns (bool);
function maxNumberOfInvites() external view returns (uint256);
function setMaxNumberOfInvites(uint256 _maxNumberOfInvites) external;
function grantCreatorsInBatch(address[] calldata _users, bool[] calldata _perms) external returns (bool);
function canCreate(address _user) external view returns (bool);
function canJoinAGarden(address _garden, address _user) external view returns (bool);
function canVoteInAGarden(address _garden, address _user) external view returns (bool);
function canAddStrategiesInAGarden(address _garden, address _user) external view returns (bool);
}
|
PRIVILEGED GOVERNANCE FUNCTION. Pause some smartcontracts in a batch process in case of unexpected issue Only the governance can unpause it _address Addresses of protocol smartcontract to be paused _state Boolean pause state/
|
function setSomePause(address[] memory _address, bool _state) external override returns (bool) {
require(
msg.sender == guardian || msg.sender == owner(),
'only pause guardian and owner can pause individually'
);
require(msg.sender == owner() || _state == true, 'only admin can unpause');
for (uint256 i = 0; i < _address.length; i++) {
guardianPaused[_address[i]] = _state;
emit ActionPausedIndividually('Guardian individual pause', _address[i], _state);
}
return _state;
}
| 13,484,943 |
./full_match/43114/0x0E96D377abC9836E3f2c71245Cc878349BE0e9c1/sources/contracts/DependencyController.sol
|
Notify all dependent contracts after role change
|
function updateRoleCache(uint256 role, address contr) public override {
EnumerableSet.AddressSet storage listeners = dependentsByRole[role];
uint256 len = listeners.length();
for (uint256 i = 0; len > i; i++) {
RoleAware(listeners.at(i)).updateRoleCache(role, contr);
}
}
| 4,606,213 |
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
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);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @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);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
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);
}
}
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];
}
}
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;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
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);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @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);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
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);
}
}
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];
}
}
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;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
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);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @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);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
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);
}
}
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];
}
}
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;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
|
Calculating NRT to be released to each of the pools sending tokens to respective wallets and emitting events Reseting NRT
|
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
| 12,590,533 |
pragma solidity 0.4.20;
/**
* @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;
}
}
contract ERC20 {
function totalSupply()public view returns(uint total_Supply);
function balanceOf(address who)public view returns(uint256);
function allowance(address owner, address spender)public view returns(uint);
function transferFrom(address from, address to, uint value)public returns(bool ok);
function approve(address spender, uint value)public returns(bool ok);
function transfer(address to, uint value)public returns(bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract IDMONEY is ERC20
{
using SafeMath for uint256;
// Name of the token
string public constant name = "IDMONEY";
// Symbol of token
string public constant symbol = "IDM";
uint8 public constant decimals = 18;
uint public _totalsupply = 35000000 * 10 ** 18; // 35 Million IDM Coins
uint256 constant public _price_tokn = 0.00075 ether;
uint256 no_of_tokens;
uint256 bonus_token;
uint256 total_token;
uint256 tokensold;
uint256 public total_token_sold;
bool stopped = false;
address public owner;
address superAdmin = 0x1313d38e988526A43Ab79b69d4C94dD16f4c9936;
address socialOne = 0x52d4bcF6F328492453fAfEfF9d6Eb73D26766Cff;
address socialTwo = 0xbFe47a096486B564783f261B324e198ad84Fb8DE;
address founderOne = 0x5AD7cdD7Cd67Fe7EB17768F04425cf35a91587c9;
address founderTwo = 0xA90ab8B8Cfa553CC75F9d2C24aE7148E44Cd0ABa;
address founderThree = 0xd2fdE07Ee7cB86AfBE59F4efb9fFC1528418CC0E;
address storage1 = 0x5E948d1C6f7C76853E43DbF1F01dcea5263011C5;
mapping(address => uint) balances;
mapping(address => bool) public refund; //checks the refund status
mapping(address => bool) public whitelisted; //checks the whitelist status of the address
mapping(address => uint256) public deposited; //checks the actual ether given by investor
mapping(address => uint256) public tokensinvestor; //checks number of tokens for investor
mapping(address => mapping(address => uint)) allowed;
uint constant public minimumInvestment = 1 ether; // 1 ether is minimum minimumInvestment
uint bonus;
uint c;
uint256 lefttokens;
enum Stages {
NOTSTARTED,
ICO,
PAUSED,
ENDED
}
Stages public stage;
modifier atStage(Stages _stage) {
require (stage == _stage);
// Contract not in expected state
_;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
modifier onlySuperAdmin() {
require (msg.sender == superAdmin);
_;
}
function IDMONEY() public
{
owner = msg.sender;
balances[superAdmin] = 2700000 * 10 ** 18; // 2.7 million given to superAdmin
balances[socialOne] = 3500000 * 10 ** 18; // 3.5 million given to socialOne
balances[socialTwo] = 3500000 * 10 ** 18; // 3.5 million given to socialTwo
balances[founderOne] = 2100000 * 10 ** 18; // 2.1 million given to FounderOne
balances[founderTwo] = 2100000 * 10 ** 18; // 2.1 million given to FounderTwo
balances[founderThree] = 2100000 * 10 ** 18; //2.1 million given to founderThree
balances[storage1] = 9000000 * 10 ** 18; // 9 million given to storage1
stage = Stages.NOTSTARTED;
Transfer(0, superAdmin, balances[superAdmin]);
Transfer(0, socialOne, balances[socialOne]);
Transfer(0, socialTwo, balances[socialTwo]);
Transfer(0, founderOne, balances[founderOne]);
Transfer(0, founderTwo, balances[founderTwo]);
Transfer(0, founderThree, balances[founderThree]);
Transfer(0, storage1, balances[storage1]);
}
function () public payable atStage(Stages.ICO)
{
require(msg.value >= minimumInvestment);
require(!stopped && msg.sender != owner);
no_of_tokens = ((msg.value).div(_price_tokn)).mul(10 ** 18);
tokensold = (tokensold).add(no_of_tokens);
deposited[msg.sender] = deposited[msg.sender].add(msg.value);
bonus = bonuscal();
bonus_token = ((no_of_tokens).mul(bonus)).div(100); // bonus
total_token = no_of_tokens + bonus_token;
total_token_sold = (total_token_sold).add(total_token);
tokensinvestor[msg.sender] = tokensinvestor[msg.sender].add(total_token);
}
//calculation for the bonus for 1 million tokens
function bonuscal() private returns(uint)
{
c = tokensold / 10 ** 23;
if (c == 0)
{
return 90;
}
return (90 - (c * 10));
}
function start_ICO() external onlyOwner atStage(Stages.NOTSTARTED)
{
stage = Stages.ICO;
stopped = false;
balances[address(this)] = 10000000 * 10 ** 18; // 10 million to smart contract initially
Transfer(0, address(this), balances[address(this)]);
}
function enablerefund(address refundaddress) external onlyOwner
{
require(!whitelisted[refundaddress]);
refund[refundaddress] = true;
}
//refund of the Non whitelisted
function claimrefund(address investor) public
{
require(refund[investor]);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
tokensinvestor[investor] = 0;
// Refunded(investor, depositedValue);
}
// called by the owner, pause ICO
function PauseICO() external onlyOwner atStage(Stages.ICO) {
stopped = true;
stage = Stages.PAUSED;
}
// called by the owner , resumes ICO
function releaseICO() external onlyOwner atStage(Stages.PAUSED)
{
stopped = false;
stage = Stages.ICO;
}
function setWhiteListAddresses(address _investor) external onlyOwner{
whitelisted[_investor] = true;
}
//Investor can claim his tokens within two weeks of ICO end using this function
//It can be also used to claim on behalf of any investor
function claimTokensICO(address receiver) public
// isValidPayload
{
// if (receiver == 0)
// receiver = msg.sender;
require(whitelisted[receiver]);
require(tokensinvestor[receiver] > 0);
uint256 tokensclaim = tokensinvestor[receiver];
balances[address(this)] = (balances[address(this)]).sub(tokensclaim);
balances[receiver] = (balances[receiver]).add(tokensclaim);
tokensinvestor[receiver] = 0;
Transfer(address(this), receiver, balances[receiver]);
}
function end_ICO() external onlySuperAdmin atStage(Stages.ICO)
{
stage = Stages.ENDED;
lefttokens = balances[address(this)];
balances[superAdmin]=(balances[superAdmin]).add(lefttokens);
balances[address(this)] = 0;
Transfer(address(this), superAdmin, lefttokens);
}
// what is the total supply of the ech tokens
function totalSupply() public view returns(uint256 total_Supply) {
total_Supply = _totalsupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner)public view returns(uint256 balance) {
return balances[_owner];
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from, address _to, uint256 _amount)public returns(bool success) {
require(_to != 0x0);
require(_amount >= 0);
balances[_from] = (balances[_from]).sub(_amount);
allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
Transfer(_from, _to, _amount);
return true;
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount)public returns(bool success) {
require(_spender != 0x0);
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender)public view returns(uint256 remaining) {
require(_owner != 0x0 && _spender != 0x0);
return allowed[_owner][_spender];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount)public returns(bool success) {
require(_to != 0x0);
require(balances[msg.sender] >= _amount && _amount >= 0);
balances[msg.sender] = (balances[msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
//In case the ownership needs to be transferred
function transferOwnership(address newOwner)public onlySuperAdmin
{
require(newOwner != 0x0);
owner = newOwner;
}
function drain() external onlyOwner {
superAdmin.transfer(this.balance);
}
}
|
Transfer the balance from owner's account to another account
|
function transfer(address _to, uint256 _amount)public returns(bool success) {
require(_to != 0x0);
require(balances[msg.sender] >= _amount && _amount >= 0);
balances[msg.sender] = (balances[msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
| 1,801,443 |
./partial_match/1/0x9992e9341e496bE5bC8F424DFC1f78A7388D3A58/sources/DEXAdapter.sol
|
Returns the Shifter address for the given ERC20Shifted token contract address. _tokenAddress The address of the ERC20Shifted token contract.
|
function getShifterByToken(address _tokenAddress) external view returns (IShifter) {
return IShifter(shifterByToken[_tokenAddress]);
}
| 16,141,016 |
pragma solidity 0.5.16;
// INTERFACE
interface IERC20Mintable {
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function mint(address _to, uint256 _value) external returns (bool);
function balanceOf(address _account) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
/**
* @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);
}
// LIB
/**
* @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 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");
}
}
}
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt(int256 x) internal pure returns (int128) {
require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt(int128 x) internal pure returns (int64) {
return int64(x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt(int128 x) internal pure returns (uint64) {
require(x >= 0);
return uint64(x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128(int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128(int128 x) internal pure returns (int256) {
return int256(x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul(int128 x, int128 y) internal pure returns (int128) {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli(int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require(
y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000
);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu(x, uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256(absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require(x >= 0);
uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(x) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div(int128 x, int128 y) internal pure returns (int128) {
require(y != 0);
int256 result = (int256(x) << 64) / y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi(int256 x, int256 y) internal pure returns (int128) {
require(y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu(uint256(x), uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -int128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu(uint256 x, uint256 y) internal pure returns (int128) {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg(int128 x) internal pure returns (int128) {
require(x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs(int128 x) internal pure returns (int128) {
require(x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv(int128 x) internal pure returns (int128) {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg(int128 x, int128 y) internal pure returns (int128) {
return int128((int256(x) + int256(y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg(int128 x, int128 y) internal pure returns (int128) {
int256 m = int256(x) * int256(y);
require(m >= 0);
require(m < 0x4000000000000000000000000000000000000000000000000000000000000000);
return int128(sqrtu(uint256(m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow(int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128(x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x2 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x4 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x8 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) {
absX <<= 32;
absXShift -= 32;
}
if (absX < 0x10000000000000000000000000000) {
absX <<= 16;
absXShift -= 16;
}
if (absX < 0x1000000000000000000000000000000) {
absX <<= 8;
absXShift -= 8;
}
if (absX < 0x10000000000000000000000000000000) {
absX <<= 4;
absXShift -= 4;
}
if (absX < 0x40000000000000000000000000000000) {
absX <<= 2;
absXShift -= 2;
}
if (absX < 0x80000000000000000000000000000000) {
absX <<= 1;
absXShift -= 1;
}
uint256 resultShift = 0;
while (y != 0) {
require(absXShift < 64);
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = (absX * absX) >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require(resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256(absResult) : int256(absResult);
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt(int128 x) internal pure returns (int128) {
require(x >= 0);
return int128(sqrtu(uint256(x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2(int128 x) internal pure returns (int128) {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(x) << uint256(127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
require(x > 0);
return int128((uint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2(int128 x) internal pure returns (int128) {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;
result >>= uint256(63 - (x >> 64));
require(result <= uint256(MAX_64x64));
return int128(result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp(int128 x) internal pure returns (int128) {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2(int128((int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) private pure returns (uint128) {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
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 uint128(r < r1 ? r : r1);
}
}
}
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant POSITIVE_ZERO = 0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant NEGATIVE_ZERO = 0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant NEGATIVE_INFINITY = 0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt(int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt(bytes16 x) internal pure returns (int256) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256(result);
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt(uint256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
uint256 result = x;
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112);
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt(bytes16 x) internal pure returns (uint256) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require(uint128(x) < 0x80000000000000000000000000000000); // Negative
require(exponent <= 16638); // Overflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128(int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16255 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128(bytes16 x) internal pure returns (int256) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256(result);
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64(int128 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint128(x > 0 ? x : -x);
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16319 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64(bytes16 x) internal pure returns (int128) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000);
return -int128(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(result);
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple(bytes32 x) internal pure returns (bytes16) {
bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0;
uint256 exponent = (uint256(x) >> 236) & 0x7FFFF;
uint256 significand = uint256(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
}
if (exponent > 278526) return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else if (exponent < 245649) return negative ? NEGATIVE_ZERO : POSITIVE_ZERO;
else if (exponent < 245761) {
significand =
(significand | 0x100000000000000000000000000000000000000000000000000000000000) >>
(245885 - exponent);
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128(significand | (exponent << 112));
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16(result);
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple(bytes16 x) internal pure returns (bytes32) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF)
exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb(result);
result = (result << (236 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128(x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32(result);
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble(bytes8 x) internal pure returns (bytes16) {
uint256 exponent = (uint64(x) >> 52) & 0x7FF;
uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF)
exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb(result);
result = (result << (112 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble(bytes16 x) internal pure returns (bytes8) {
bool negative = uint128(x) >= 0x80000000000000000000000000000000;
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000;
// NaN
else
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000);
// Infinity
else if (exponent < 15309)
return
negative
? bytes8(0x8000000000000000) // -0
: bytes8(0x0000000000000000);
// 0
else if (exponent < 15361) {
significand = (significand | 0x10000000000000000000000000000) >> (15421 - exponent);
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64(significand | (exponent << 52));
if (negative) result |= 0x8000000000000000;
return bytes8(result);
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN(bytes16 x) internal pure returns (bool) {
return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF > 0x7FFF0000000000000000000000000000;
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity(bytes16 x) internal pure returns (bool) {
return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x7FFF0000000000000000000000000000;
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign(bytes16 x) internal pure returns (int8) {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128(x) >= 0x80000000000000000000000000000000) return -1;
else return 1;
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX = uint128(x) >= 0x80000000000000000000000000000000;
bool negativeY = uint128(y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8(1) : -1;
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq(bytes16 x, bytes16 y) internal pure returns (bool) {
if (x == y) {
return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF < 0x7FFF0000000000000000000000000000;
} else return false;
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add(bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128(x) >= 0x80000000000000000000000000000000;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128(y) >= 0x80000000000000000000000000000000;
uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return y == NEGATIVE_ZERO ? POSITIVE_ZERO : y;
else if (ySignifier == 0) return x == NEGATIVE_ZERO ? POSITIVE_ZERO : x;
else {
int256 delta = int256(xExponent) - int256(yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256(delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256(-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF) return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000) xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return
bytes16(
uint128(
(xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier
)
);
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1) ySignifier = ((ySignifier - 1) >> uint256(delta - 1)) + 1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1) xSignifier = ((xSignifier - 1) >> uint256(-delta - 1)) + 1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0) return POSITIVE_ZERO;
uint256 msb = msb(xSignifier);
if (msb == 113) {
xSignifier = (xSignifier >> 1) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier = (xSignifier << shift) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF) return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else
return
bytes16(
uint128(
(xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier
)
);
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) {
return add(x, y ^ 0x80000000000000000000000000000000);
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x ^ (y & 0x80000000000000000000000000000000);
else if (x ^ y == 0x80000000000000000000000000000000) return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ (x & 0x80000000000000000000000000000000);
} else {
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb = xSignifier >= 0x200000000000000000000000000000000000000000000000000000000
? 225
: xSignifier >= 0x100000000000000000000000000000000000000000000000000000000
? 224
: msb(xSignifier);
if (xExponent + msb < 16496) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) {
// Subnormal
if (xExponent < 16496) xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496) xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112) xSignifier >>= msb - 112;
else if (msb < 112) xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return
bytes16(
uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | (xExponent << 112) | xSignifier)
);
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div(bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else return POSITIVE_ZERO | ((x ^ y) & 0x80000000000000000000000000000000);
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return POSITIVE_INFINITY | ((x ^ y) & 0x80000000000000000000000000000000);
} else {
uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint256 shift = 226 - msb(xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
} else {
xSignifier = (xSignifier | 0x10000000000000000000000000000) << 114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO;
assert(xSignifier >= 0x1000000000000000000000000000);
uint256 msb = xSignifier >= 0x80000000000000000000000000000
? msb(xSignifier)
: xSignifier >= 0x40000000000000000000000000000
? 114
: xSignifier >= 0x20000000000000000000000000000
? 113
: 112;
if (xExponent + msb > yExponent + 16497) {
// Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) {
// Subnormal
if (xExponent + 16380 > yExponent) xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent) xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else {
// Normal
if (msb > 112) xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return
bytes16(
uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | (xExponent << 112) | xSignifier)
);
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg(bytes16 x) internal pure returns (bytes16) {
return x ^ 0x80000000000000000000000000000000;
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs(bytes16 x) internal pure returns (bytes16) {
return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt(bytes16 x) internal pure returns (bytes16) {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = (xExponent + 16383) >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 113;
else {
uint256 msb = msb(xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 112;
else {
uint256 msb = msb(xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return bytes16(uint128((xExponent << 112) | (r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)));
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2(bytes16 x) internal pure returns (bytes16) {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000) return POSITIVE_ZERO;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = msb(xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift = 112 - msb(resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (resultSignifier < 0x10000000000000000000000000000) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return
bytes16(
uint128(
(resultNegative ? 0x80000000000000000000000000000000 : 0) |
(resultExponent << 112) |
(resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln(bytes16 x) internal pure returns (bytes16) {
return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2(bytes16 x) internal pure returns (bytes16) {
bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397) return xNegative ? POSITIVE_ZERO : POSITIVE_INFINITY;
else if (xExponent < 16255) return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367) xSignifier <<= xExponent - 16367;
else if (xExponent < 16367) xSignifier >>= 16367 - xExponent;
if (xNegative && xSignifier > 0x406E00000000000000000000000000000000) return POSITIVE_ZERO;
if (!xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (xSignifier & 0x40000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (xSignifier & 0x20000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (xSignifier & 0x10000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (xSignifier & 0x8000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (xSignifier & 0x4000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (xSignifier & 0x2000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (xSignifier & 0x1000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (xSignifier & 0x800000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (xSignifier & 0x400000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (xSignifier & 0x200000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (xSignifier & 0x100000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (xSignifier & 0x80000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (xSignifier & 0x40000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (xSignifier & 0x20000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000162E525EE054754457D5995292026) >> 128;
if (xSignifier & 0x10000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (xSignifier & 0x8000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (xSignifier & 0x4000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (xSignifier & 0x2000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (xSignifier & 0x1000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (xSignifier & 0x800000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (xSignifier & 0x400000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (xSignifier & 0x200000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (xSignifier & 0x100000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (xSignifier & 0x80000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (xSignifier & 0x40000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (xSignifier & 0x20000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (xSignifier & 0x10000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (xSignifier & 0x8000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (xSignifier & 0x4000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (xSignifier & 0x2000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (xSignifier & 0x1000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (xSignifier & 0x800000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (xSignifier & 0x400000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (xSignifier & 0x200000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (xSignifier & 0x100000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (xSignifier & 0x80000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (xSignifier & 0x40000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (xSignifier & 0x20000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (xSignifier & 0x10000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (xSignifier & 0x8000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (xSignifier & 0x4000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (xSignifier & 0x2000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (xSignifier & 0x1000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (xSignifier & 0x800000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (xSignifier & 0x400000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (xSignifier & 0x200000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (xSignifier & 0x100000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (xSignifier & 0x80000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (xSignifier & 0x40000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (xSignifier & 0x20000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (xSignifier & 0x10000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (xSignifier & 0x8000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (xSignifier & 0x4000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (xSignifier & 0x2000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (xSignifier & 0x1000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (xSignifier & 0x800000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (xSignifier & 0x400000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (xSignifier & 0x200000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (xSignifier & 0x100000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (xSignifier & 0x80000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (xSignifier & 0x40000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (xSignifier & 0x20000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (xSignifier & 0x10000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000B17217F7D1CF79AB) >> 128;
if (xSignifier & 0x8000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5) >> 128;
if (xSignifier & 0x4000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000002C5C85FDF473DE6A) >> 128;
if (xSignifier & 0x2000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000162E42FEFA39EF34) >> 128;
if (xSignifier & 0x1000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000B17217F7D1CF799) >> 128;
if (xSignifier & 0x800000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000058B90BFBE8E7BCC) >> 128;
if (xSignifier & 0x400000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000002C5C85FDF473DE5) >> 128;
if (xSignifier & 0x200000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000162E42FEFA39EF2) >> 128;
if (xSignifier & 0x100000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000B17217F7D1CF78) >> 128;
if (xSignifier & 0x80000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000058B90BFBE8E7BB) >> 128;
if (xSignifier & 0x40000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000002C5C85FDF473DD) >> 128;
if (xSignifier & 0x20000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000162E42FEFA39EE) >> 128;
if (xSignifier & 0x10000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000B17217F7D1CF6) >> 128;
if (xSignifier & 0x8000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000058B90BFBE8E7A) >> 128;
if (xSignifier & 0x4000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000002C5C85FDF473C) >> 128;
if (xSignifier & 0x2000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000162E42FEFA39D) >> 128;
if (xSignifier & 0x1000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000B17217F7D1CE) >> 128;
if (xSignifier & 0x800000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000058B90BFBE8E6) >> 128;
if (xSignifier & 0x400000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000002C5C85FDF472) >> 128;
if (xSignifier & 0x200000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000162E42FEFA38) >> 128;
if (xSignifier & 0x100000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000B17217F7D1B) >> 128;
if (xSignifier & 0x80000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000058B90BFBE8D) >> 128;
if (xSignifier & 0x40000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000002C5C85FDF46) >> 128;
if (xSignifier & 0x20000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000162E42FEFA2) >> 128;
if (xSignifier & 0x10000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000B17217F7D0) >> 128;
if (xSignifier & 0x8000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000058B90BFBE7) >> 128;
if (xSignifier & 0x4000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000002C5C85FDF3) >> 128;
if (xSignifier & 0x2000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000162E42FEF9) >> 128;
if (xSignifier & 0x1000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000B17217F7C) >> 128;
if (xSignifier & 0x800000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000058B90BFBD) >> 128;
if (xSignifier & 0x400000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000002C5C85FDE) >> 128;
if (xSignifier & 0x200000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000162E42FEE) >> 128;
if (xSignifier & 0x100000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000B17217F6) >> 128;
if (xSignifier & 0x80000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000058B90BFA) >> 128;
if (xSignifier & 0x40000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000002C5C85FC) >> 128;
if (xSignifier & 0x20000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000162E42FD) >> 128;
if (xSignifier & 0x10000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000B17217E) >> 128;
if (xSignifier & 0x8000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000058B90BE) >> 128;
if (xSignifier & 0x4000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000002C5C85E) >> 128;
if (xSignifier & 0x2000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000162E42E) >> 128;
if (xSignifier & 0x1000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000B17216) >> 128;
if (xSignifier & 0x800000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000058B90A) >> 128;
if (xSignifier & 0x400000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000002C5C84) >> 128;
if (xSignifier & 0x200000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000162E41) >> 128;
if (xSignifier & 0x100000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000B1720) >> 128;
if (xSignifier & 0x80000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000058B8F) >> 128;
if (xSignifier & 0x40000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000002C5C7) >> 128;
if (xSignifier & 0x20000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000162E3) >> 128;
if (xSignifier & 0x10000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000000B171) >> 128;
if (xSignifier & 0x8000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000058B8) >> 128;
if (xSignifier & 0x4000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000002C5B) >> 128;
if (xSignifier & 0x2000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000000162D) >> 128;
if (xSignifier & 0x1000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000000B16) >> 128;
if (xSignifier & 0x800 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000000058A) >> 128;
if (xSignifier & 0x400 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000002C4) >> 128;
if (xSignifier & 0x200 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000000161) >> 128;
if (xSignifier & 0x100 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000000B0) >> 128;
if (xSignifier & 0x80 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000057) >> 128;
if (xSignifier & 0x40 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000002B) >> 128;
if (xSignifier & 0x20 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000015) >> 128;
if (xSignifier & 0x10 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000000A) >> 128;
if (xSignifier & 0x8 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000004) >> 128;
if (xSignifier & 0x4 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000001) >> 128;
if (!xNegative) {
resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier = resultSignifier >> (resultExponent - 16367);
resultExponent = 0;
}
return bytes16(uint128((resultExponent << 112) | resultSignifier));
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp(bytes16 x) internal pure returns (bytes16) {
return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function msb(uint256 x) private pure returns (uint256) {
require(x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
result += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
result += 64;
}
if (x >= 0x100000000) {
x >>= 32;
result += 32;
}
if (x >= 0x10000) {
x >>= 16;
result += 16;
}
if (x >= 0x100) {
x >>= 8;
result += 8;
}
if (x >= 0x10) {
x >>= 4;
result += 4;
}
if (x >= 0x4) {
x >>= 2;
result += 2;
}
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
}
// CONTRACTS
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract Sacrifice {
constructor(address payable _recipient) public payable {
selfdestruct(_recipient);
}
}
/**
* @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.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMathERC20 {
function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// 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;
}
}
/*
* @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.
*/
/**
* @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 Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
contract StakingV2 is Ownable, ReentrancyGuard {
using Address for address;
using SafeMath for uint256;
using SafeERC20 for IERC20;
// EVENTS
/**
* @dev Emitted when a user deposits tokens.
* @param sender User address.
* @param id User's unique deposit ID.
* @param amount The amount of deposited tokens.
* @param currentBalance Current user balance.
* @param timestamp Operation date
*/
event Deposited(
address indexed sender,
uint256 indexed id,
uint256 amount,
uint256 currentBalance,
uint256 timestamp
);
/**
* @dev Emitted when a user withdraws tokens.
* @param sender User address.
* @param id User's unique deposit ID.
* @param totalWithdrawalAmount The total amount of withdrawn tokens.
* @param currentBalance Balance before withdrawal
* @param timestamp Operation date
*/
event WithdrawnAll(
address indexed sender,
uint256 indexed id,
uint256 totalWithdrawalAmount,
uint256 currentBalance,
uint256 timestamp
);
/**
* @dev Emitted when a user extends lockup.
* @param sender User address.
* @param id User's unique deposit ID.
* @param currentBalance Balance before lockup extension
* @param finalBalance Final balance
* @param timestamp The instant when the lockup is extended.
*/
event ExtendedLockup(
address indexed sender,
uint256 indexed id,
uint256 currentBalance,
uint256 finalBalance,
uint256 timestamp
);
/**
* @dev Emitted when a new Liquidity Provider address value is set.
* @param value A new address value.
* @param sender The owner address at the moment of address changing.
*/
event LiquidityProviderAddressSet(address value, address sender);
struct AddressParam {
address oldValue;
address newValue;
uint256 timestamp;
}
// The deposit user balaces
mapping(address => mapping(uint256 => uint256)) public balances;
// The dates of users deposits/withdraws/extendLockups
mapping(address => mapping(uint256 => uint256)) public depositDates;
// Variable that prevents _deposit method from being called 2 times TODO CHECK
bool private locked;
// Variable to pause all operations
bool private contractPaused = false;
bool private pausedDepositsAndLockupExtensions = false;
// STAKE token
IERC20Mintable public token;
// Reward Token
IERC20Mintable public tokenReward;
// The address for the Liquidity Providers
AddressParam public liquidityProviderAddressParam;
uint256 private constant DAY = 1 days;
uint256 private constant MONTH = 30 days;
uint256 private constant YEAR = 365 days;
// The period after which the new value of the parameter is set
uint256 public constant PARAM_UPDATE_DELAY = 7 days;
// MODIFIERS
/*
* 1 | 2 | 3 | 4 | 5
* 0 Months | 3 Months | 6 Months | 9 Months | 12 Months
*/
modifier validDepositId(uint256 _depositId) {
require(_depositId >= 1 && _depositId <= 5, "Invalid depositId");
_;
}
// Impossible to withdrawAll if you have never deposited.
modifier balanceExists(uint256 _depositId) {
require(balances[msg.sender][_depositId] > 0, "Your deposit is zero");
_;
}
modifier isNotLocked() {
require(locked == false, "Locked, try again later");
_;
}
modifier isNotPaused() {
require(contractPaused == false, "Paused");
_;
}
modifier isNotPausedOperations() {
require(contractPaused == false, "Paused");
_;
}
modifier isNotPausedDepositAndLockupExtensions() {
require(pausedDepositsAndLockupExtensions == false, "Paused Deposits and Extensions");
_;
}
/**
* @dev Pause Deposits, Withdraw, Lockup Extension
*/
function pauseContract(bool value) public onlyOwner {
contractPaused = value;
}
/**
* @dev Pause Deposits and Lockup Extension
*/
function pauseDepositAndLockupExtensions(bool value) public onlyOwner {
pausedDepositsAndLockupExtensions = value;
}
/**
* @dev Initializes the contract. _tokenAddress _tokenReward will have the same address
* @param _owner The owner of the contract.
* @param _tokenAddress The address of the STAKE token contract.
* @param _tokenReward The address of token rewards.
* @param _liquidityProviderAddress The address for the Liquidity Providers reward.
*/
function initializeStaking(
address _owner,
address _tokenAddress,
address _tokenReward,
address _liquidityProviderAddress
) external initializer {
require(_owner != address(0), "Zero address");
require(_tokenAddress.isContract(), "Not a contract address");
Ownable.initialize(msg.sender);
ReentrancyGuard.initialize();
token = IERC20Mintable(_tokenAddress);
tokenReward = IERC20Mintable(_tokenReward);
setLiquidityProviderAddress(_liquidityProviderAddress);
Ownable.transferOwnership(_owner);
}
/**
* @dev Sets the address for the Liquidity Providers reward.
* Can only be called by owner.
* @param _address The new address.
*/
function setLiquidityProviderAddress(address _address) public onlyOwner {
require(_address != address(0), "Zero address");
require(_address != address(this), "Wrong address");
AddressParam memory param = liquidityProviderAddressParam;
if (param.timestamp == 0) {
param.oldValue = _address;
} else if (_paramUpdateDelayElapsed(param.timestamp)) {
param.oldValue = param.newValue;
}
param.newValue = _address;
param.timestamp = _now();
liquidityProviderAddressParam = param;
emit LiquidityProviderAddressSet(_address, msg.sender);
}
/**
* @return Returns true if param update delay elapsed.
*/
function _paramUpdateDelayElapsed(uint256 _paramTimestamp) internal view returns (bool) {
return _now() > _paramTimestamp.add(PARAM_UPDATE_DELAY);
}
/**
* @dev This method is used to deposit tokens to the deposit opened before.
* It calls the internal "_deposit" method and transfers tokens from sender to contract.
* Sender must approve tokens first.
*
* Instead this, user can use the simple "transferFrom" method of OVR token contract to make a deposit.
*
* @param _depositId User's unique deposit ID.
* @param _amount The amount to deposit.
*/
function deposit(uint256 _depositId, uint256 _amount)
public
validDepositId(_depositId)
isNotLocked
isNotPaused
isNotPausedDepositAndLockupExtensions
{
require(_amount > 0, "Amount should be more than 0");
_deposit(msg.sender, _depositId, _amount);
_setLocked(true);
require(token.transferFrom(msg.sender, address(this), _amount), "Transfer failed");
_setLocked(false);
}
/**
* @param _sender The address of the sender.
* @param _depositId User's deposit ID.
* @param _amount The amount to deposit.
*/
function _deposit(
address _sender,
uint256 _depositId,
uint256 _amount
) internal nonReentrant {
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance = calcRewards(_sender, _depositId);
uint256 timestamp = _now();
balances[_sender][_depositId] = _amount.add(finalBalance);
depositDates[_sender][_depositId] = _now();
emit Deposited(_sender, _depositId, _amount, currentBalance, timestamp);
}
/**
* @dev This method is used to withdraw rewards and balance.
* It calls the internal "_withdrawAll" method.
* @param _depositId User's unique deposit ID
*/
function withdrawAll(uint256 _depositId) external balanceExists(_depositId) validDepositId(_depositId) isNotPaused {
require(isLockupPeriodExpired(_depositId), "Too early, Lockup period");
_withdrawAll(msg.sender, _depositId);
}
function _withdrawAll(address _sender, uint256 _depositId)
internal
balanceExists(_depositId)
validDepositId(_depositId)
nonReentrant
{
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance = calcRewards(_sender, _depositId);
require(finalBalance > 0, "Nothing to withdraw");
balances[_sender][_depositId] = 0;
_setLocked(true);
require(tokenReward.transfer(_sender, finalBalance), "Liquidity pool transfer failed");
_setLocked(false);
emit WithdrawnAll(_sender, _depositId, finalBalance, currentBalance, _now());
}
/**
* This method is used to extend lockup. It is available if your lockup period is expired and if depositId != 1
* It calls the internal "_extendLockup" method.
* @param _depositId User's unique deposit ID
*/
function extendLockup(uint256 _depositId)
external
balanceExists(_depositId)
validDepositId(_depositId)
isNotPaused
isNotPausedDepositAndLockupExtensions
{
require(_depositId != 1, "No lockup is set up");
_extendLockup(msg.sender, _depositId);
}
function _extendLockup(address _sender, uint256 _depositId) internal nonReentrant {
uint256 timestamp = _now();
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance = calcRewards(_sender, _depositId);
balances[_sender][_depositId] = finalBalance;
depositDates[_sender][_depositId] = timestamp;
emit ExtendedLockup(_sender, _depositId, currentBalance, finalBalance, timestamp);
}
function isLockupPeriodExpired(uint256 _depositId) public view validDepositId(_depositId) returns (bool) {
uint256 lockPeriod;
if (_depositId == 1) {
lockPeriod = 0;
} else if (_depositId == 2) {
lockPeriod = MONTH * 3; // 3 months
} else if (_depositId == 3) {
lockPeriod = MONTH * 6; // 6 months
} else if (_depositId == 4) {
lockPeriod = MONTH * 9; // 9 months
} else if (_depositId == 5) {
lockPeriod = MONTH * 12; // 12 months
}
if (_now() > depositDates[msg.sender][_depositId].add(lockPeriod)) {
return true;
} else {
return false;
}
}
function pow(int128 _x, uint256 _n) public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt(1);
while (_n > 0) {
if (_n % 2 == 1) {
r = ABDKMath64x64.mul(r, _x);
_n -= 1;
} else {
_x = ABDKMath64x64.mul(_x, _x);
_n /= 2;
}
}
}
/**
* This method is calcuate final compouded capital.
* @param _principal User's balance
* @param _ratio Interest rate
* @param _n Periods is timestamp
* @return finalBalance The final compounded capital
*
* A = C ( 1 + rate )^t
*/
function compound(
uint256 _principal,
uint256 _ratio,
uint256 _n
) public view returns (uint256) {
uint256 daysCount = _n.div(DAY);
return
ABDKMath64x64.mulu(
pow(ABDKMath64x64.add(ABDKMath64x64.fromUInt(1), ABDKMath64x64.divu(_ratio, 10**18)), daysCount),
_principal
);
}
/**
* This moethod is used to calculate final compounded balance and is based on deposit duration and deposit id.
* Each deposit mode is characterized by the lockup period and interest rate.
* At the expiration of the lockup period the final compounded capital
* will use minimum interest rate.
*
* This function can be called at any time to get the current total reward.
* @param _sender Sender Address.
* @param _depositId The depositId
* @return finalBalance The final compounded capital
*/
function calcRewards(address _sender, uint256 _depositId) public view validDepositId(_depositId) returns (uint256) {
uint256 timePassed = _now().sub(depositDates[_sender][_depositId]);
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance;
uint256 ratio;
uint256 lockPeriod;
if (_depositId == 1) {
ratio = 100000000000000; // APY 3.7% InterestRate = 0.01
lockPeriod = 0;
} else if (_depositId == 2) {
ratio = 300000000000000; // APY 11.6% InterestRate = 0.03
lockPeriod = MONTH * 3; // 3 months
} else if (_depositId == 3) {
ratio = 400000000000000; // APY 15.7% InterestRate = 0.04
lockPeriod = MONTH * 6; // 6 months
} else if (_depositId == 4) {
ratio = 600000000000000; // APY 25.5% InterestRate = 0.06
lockPeriod = MONTH * 9; // 9 months
} else if (_depositId == 5) {
ratio = 800000000000000; // APY 33.9% InterestRate = 0.08
lockPeriod = YEAR; // 12 months
}
// You can't have earnings without balance
if (currentBalance == 0) {
return finalBalance = 0;
}
// No lockup
if (_depositId == 1) {
finalBalance = compound(currentBalance, ratio, timePassed);
return finalBalance;
}
// If you have an uncovered period from lockup, you still get rewards at the minimum rate
if (timePassed > lockPeriod) {
uint256 rewardsWithLockup = compound(currentBalance, ratio, lockPeriod).sub(currentBalance);
finalBalance = compound(rewardsWithLockup.add(currentBalance), 100000000000000, timePassed.sub(lockPeriod));
return finalBalance;
}
finalBalance = compound(currentBalance, ratio, timePassed);
return finalBalance;
}
function getCurrentBalance(uint256 _depositId, address _address) public view returns (uint256 addressBalance) {
addressBalance = balances[_address][_depositId];
}
/**
* @return Returns current liquidity providers reward address.
*/
function liquidityProviderAddress() public view returns (address) {
AddressParam memory param = liquidityProviderAddressParam;
return param.newValue;
}
/**
* @dev Sets lock to prevent reentrance.
*/
function _setLocked(bool _locked) internal {
locked = _locked;
}
function senderCurrentBalance() public view returns (uint256) {
return msg.sender.balance;
}
/**
* @return Returns current timestamp.
*/
function _now() internal view returns (uint256) {
// Note that the timestamp can have a 900-second error:
// https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md
// return now; // solium-disable-line security/no-block-members
return block.timestamp;
}
}
|
Calculate binary exponent of x. Revert on overflow. x signed 64.64-bit fixed point number return signed 64.64-bit fixed point number/
|
function exp_2(int128 x) internal pure returns (int128) {
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;
result >>= uint256(63 - (x >> 64));
require(result <= uint256(MAX_64x64));
return int128(result);
}
| 6,261,395 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
contract PlagueEvents {
//infective person
event onInfectiveStage
(
address indexed player,
uint256 indexed rndNo,
uint256 keys,
uint256 eth,
uint256 timeStamp,
address indexed inveter
);
// become leader during second stage
event onDevelopmentStage
(
address indexed player,
uint256 indexed rndNo,
uint256 eth,
uint256 timeStamp,
address indexed inveter
);
// award
event onAward
(
address indexed player,
uint256 indexed rndNo,
uint256 eth,
uint256 timeStamp
);
}
contract Plague is PlagueEvents{
using SafeMath for *;
using KeysCalc for uint256;
struct Round {
uint256 eth; // total eth
uint256 keys; // total keys
uint256 startTime; // end time
uint256 endTime; // end time
uint256 infectiveEndTime; // infective end time
address leader; // leader
address infectLastPlayer; // the player will award 10% eth
address [11] lastInfective; // the lastest 11 infective
address [4] loseInfective; // the lose infective
bool [11] infectiveAward_m; //
uint256 totalInfective; // the count of this round
uint256 inveterAmount; // remain inveter amount of this round
uint256 lastRoundReward; // last round remain eth 10% + eth 4% - inveterAmount + last remain award
uint256 exAward; // development award
}
struct PlayerRound {
uint256 eth; // eth player has added to round
uint256 keys; // keys
uint256 withdraw; // how many eth has been withdraw
uint256 getInveterAmount; // inverter amount
uint256 hasGetAwardAmount; // player has get award amount
}
uint256 public rndNo = 1; // current round number
uint256 public totalEth = 0; // total eth in all round
uint256 constant private rndInfectiveStage_ = 10 minutes; // round timer at iinfective stage12 hours;
uint256 constant private rndInfectiveReadyTime_ = 1 minutes; // round timer at infective stage ready time
uint256 constant private rndDevelopmentStage_ = 3 minutes; // round timer at development stage 30 minutes;
uint256 constant private rndDevelopmentReadyTime_ = 1 minutes; // round timer at development stage ready time 1 hours;
uint256 constant private allKeys_ = 100 * (10 ** 18); // all keys count
uint256 constant private allEths_ = 7500773437500000; // all eths count
uint256 constant private rndIncreaseTime_ = 3 minutes; // increase time 3 hours
uint256 constant private developmentAwardPercent = 1; // 0.1% reduction every 3 hours
mapping (uint256 => Round) public round_m; // (rndNo => Round)
mapping (uint256 => mapping (address => PlayerRound)) public playerRound_m; // (rndNo => addr => PlayerRound)
address public owner; // owner address
address public receiver = address(0); // receive eth address
uint256 public ownerWithdraw = 0; // how many eth has been withdraw by owner
bool public isStartGame = false; // start game flag
constructor()
public
{
owner = msg.sender;
}
/**
* @dev prevents contracts from interacting
*/
modifier onlyHuman()
{
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth)
{
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
/**
* @dev only owner
*/
modifier onlyOwner()
{
require(owner == msg.sender, "only owner can do it");
_;
}
/**
* @dev It must be human beings to call the function.
*/
function isHuman(address _addr) private view returns (bool)
{
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
return _codeLength == 0;
}
/**
* @dev player infect a person at current round
*
*/
function buyKeys(address _inveter) private
{
uint256 _eth = msg.value;
uint256 _now = now;
uint256 _rndNo = rndNo;
uint256 _ethUse = msg.value;
// start next round?
if (_now > round_m[_rndNo].endTime)
{
require(round_m[_rndNo].endTime + rndDevelopmentReadyTime_ < _now, "we should wait some times");
uint256 lastAwardEth = (round_m[_rndNo].eth.mul(14) / 100).sub(round_m[_rndNo].inveterAmount);
if(round_m[_rndNo].totalInfective < round_m[_rndNo].lastInfective.length.sub(1))
{
uint256 nextPlayersAward = round_m[_rndNo].lastInfective.length.sub(1).sub(round_m[_rndNo].totalInfective);
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
if(round_m[_rndNo].infectLastPlayer != address(0))
{
lastAwardEth = lastAwardEth.add(nextPlayersAward.mul(_totalAward.mul(3)/100));
}
else
{
lastAwardEth = lastAwardEth.add(nextPlayersAward.mul(_totalAward.mul(4)/100));
}
}
_rndNo = _rndNo.add(1);
rndNo = _rndNo;
round_m[_rndNo].startTime = _now;
round_m[_rndNo].endTime = _now + rndInfectiveStage_;
round_m[_rndNo].totalInfective = 0;
round_m[_rndNo].lastRoundReward = lastAwardEth;
}
// infective or second stage
if (round_m[_rndNo].keys < allKeys_)
{
// infection stage
uint256 _keys = (round_m[_rndNo].eth).keysRec(_eth);
if (_keys.add(round_m[_rndNo].keys) >= allKeys_)
{
_keys = allKeys_.sub(round_m[_rndNo].keys);
if (round_m[_rndNo].eth >= allEths_)
{
_ethUse = 0;
}
else {
_ethUse = (allEths_).sub(round_m[_rndNo].eth);
}
if (_eth > _ethUse)
{
// refund
msg.sender.transfer(_eth.sub(_ethUse));
}
else {
// fix
_ethUse = _eth;
}
// first stage is over, record current time
round_m[_rndNo].infectiveEndTime = _now.add(rndInfectiveReadyTime_);
round_m[_rndNo].endTime = _now.add(rndDevelopmentStage_).add(rndInfectiveReadyTime_);
round_m[_rndNo].infectLastPlayer = msg.sender;
}
else
{
require (_keys >= 1 * 10 ** 19, "at least 10 thound people");
round_m[_rndNo].endTime = _now + rndInfectiveStage_;
}
round_m[_rndNo].leader = msg.sender;
// update playerRound
playerRound_m[_rndNo][msg.sender].keys = _keys.add(playerRound_m[_rndNo][msg.sender].keys);
playerRound_m[_rndNo][msg.sender].eth = _ethUse.add(playerRound_m[_rndNo][msg.sender].eth);
// update round
round_m[_rndNo].keys = _keys.add(round_m[_rndNo].keys);
round_m[_rndNo].eth = _ethUse.add(round_m[_rndNo].eth);
// update global variable
totalEth = _ethUse.add(totalEth);
// event
emit PlagueEvents.onInfectiveStage
(
msg.sender,
_rndNo,
_keys,
_ethUse,
_now,
_inveter
);
} else {
// second stage
require(round_m[_rndNo].infectiveEndTime < _now, "The virus is being prepared...");
// increase 0.05 Ether every 3 hours
_ethUse = (((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(5 * 10 ** 16)).add((5 * 10 ** 16));
require(_eth >= _ethUse, "Ether amount is wrong");
if(_eth > _ethUse)
{
msg.sender.transfer(_eth.sub(_ethUse));
}
round_m[_rndNo].endTime = _now + rndDevelopmentStage_;
round_m[_rndNo].leader = msg.sender;
// update playerRound
playerRound_m[_rndNo][msg.sender].eth = _ethUse.add(playerRound_m[_rndNo][msg.sender].eth);
// update round
round_m[_rndNo].eth = _ethUse.add(round_m[_rndNo].eth);
// update global variable
totalEth = _ethUse.add(totalEth);
// update development award
uint256 _exAwardPercent = ((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(developmentAwardPercent).add(developmentAwardPercent);
if(_exAwardPercent >= 410)
{
_exAwardPercent = 410;
}
round_m[_rndNo].exAward = (_exAwardPercent.mul(_ethUse) / 1000).add(round_m[_rndNo].exAward);
// event
emit PlagueEvents.onDevelopmentStage
(
msg.sender,
_rndNo,
_ethUse,
_now,
_inveter
);
}
// caculate share inveter amount
if(_inveter != address(0) && isHuman(_inveter))
{
playerRound_m[_rndNo][_inveter].getInveterAmount = playerRound_m[_rndNo][_inveter].getInveterAmount.add(_ethUse.mul(10) / 100);
round_m[_rndNo].inveterAmount = round_m[_rndNo].inveterAmount.add(_ethUse.mul(10) / 100);
}
round_m[_rndNo].loseInfective[round_m[_rndNo].totalInfective % 4] = round_m[_rndNo].lastInfective[round_m[_rndNo].totalInfective % 11];
round_m[_rndNo].lastInfective[round_m[_rndNo].totalInfective % 11] = msg.sender;
round_m[_rndNo].totalInfective = round_m[_rndNo].totalInfective.add(1);
}
/**
* @dev recommend a player
*/
function buyKeyByAddr(address _inveter)
onlyHuman()
isWithinLimits(msg.value)
public
payable
{
require(isStartGame == true, "The game hasn't started yet.");
buyKeys(_inveter);
}
/**
* @dev play
*/
function()
onlyHuman()
isWithinLimits(msg.value)
public
payable
{
require(isStartGame == true, "The game hasn't started yet.");
buyKeys(address(0));
}
/**
* @dev Award by rndNo.
* 0x80ec35ff
* 0x80ec35ff0000000000000000000000000000000000000000000000000000000000000001
*/
function awardByRndNo(uint256 _rndNo)
onlyHuman()
public
{
require(isStartGame == true, "The game hasn't started yet.");
require(_rndNo <= rndNo, "You're running too fast");
uint256 _ethOut = 0;
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
_totalAward = _totalAward.add(round_m[_rndNo].exAward);
uint256 _getAward = 0;
//withdraw award
uint256 _totalWithdraw = round_m[_rndNo].eth.mul(51) / 100;
_totalWithdraw = _totalWithdraw.sub(round_m[_rndNo].exAward);
_totalWithdraw = (_totalWithdraw.mul(playerRound_m[_rndNo][msg.sender].keys));
_totalWithdraw = _totalWithdraw / round_m[_rndNo].keys;
uint256 _inveterAmount = playerRound_m[_rndNo][msg.sender].getInveterAmount;
_totalWithdraw = _totalWithdraw.add(_inveterAmount);
uint256 _withdrawed = playerRound_m[_rndNo][msg.sender].withdraw;
if(_totalWithdraw > _withdrawed)
{
_ethOut = _ethOut.add(_totalWithdraw.sub(_withdrawed));
playerRound_m[_rndNo][msg.sender].withdraw = _totalWithdraw;
}
//lastest infect player
if(msg.sender == round_m[_rndNo].infectLastPlayer && round_m[_rndNo].infectLastPlayer != address(0) && round_m[_rndNo].infectiveEndTime != 0)
{
_getAward = _getAward.add(_totalAward.mul(10)/100);
}
if(now > round_m[_rndNo].endTime)
{
// finally award
if(round_m[_rndNo].leader == msg.sender)
{
_getAward = _getAward.add(_totalAward.mul(60)/100);
}
//finally ten person award
for(uint256 i = 0;i < round_m[_rndNo].lastInfective.length; i = i.add(1))
{
if(round_m[_rndNo].lastInfective[i] == msg.sender && (round_m[_rndNo].totalInfective.sub(1) % 11) != i){
if(round_m[_rndNo].infectiveAward_m[i])
continue;
if(round_m[_rndNo].infectLastPlayer != address(0))
{
_getAward = _getAward.add(_totalAward.mul(3)/100);
}
else{
_getAward = _getAward.add(_totalAward.mul(4)/100);
}
round_m[_rndNo].infectiveAward_m[i] = true;
}
}
}
_ethOut = _ethOut.add(_getAward.sub(playerRound_m[_rndNo][msg.sender].hasGetAwardAmount));
playerRound_m[_rndNo][msg.sender].hasGetAwardAmount = _getAward;
if(_ethOut != 0)
{
msg.sender.transfer(_ethOut);
}
// event
emit PlagueEvents.onAward
(
msg.sender,
_rndNo,
_ethOut,
now
);
}
/**
* @dev Get player bonus data
* 0xd982466d
* 0xd982466d0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000028f211f6c07d3b79e0aab886d56333e4027d4f59
* @return player's award
* @return player's can withdraw amount
* @return player's inveter amount
* @return player's has been withdraw
*/
function getPlayerAwardByRndNo(uint256 _rndNo, address _playAddr)
view
public
returns (uint256, uint256, uint256, uint256)
{
require(isStartGame == true, "The game hasn't started yet.");
require(_rndNo <= rndNo, "You're running too fast");
uint256 _ethPlayerAward = 0;
//withdraw award
uint256 _totalWithdraw = round_m[_rndNo].eth.mul(51) / 100;
_totalWithdraw = _totalWithdraw.sub(round_m[_rndNo].exAward);
_totalWithdraw = (_totalWithdraw.mul(playerRound_m[_rndNo][_playAddr].keys));
_totalWithdraw = _totalWithdraw / round_m[_rndNo].keys;
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
_totalAward = _totalAward.add(round_m[_rndNo].exAward);
//lastest infect player
if(_playAddr == round_m[_rndNo].infectLastPlayer && round_m[_rndNo].infectLastPlayer != address(0) && round_m[_rndNo].infectiveEndTime != 0)
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(10)/100);
}
if(now > round_m[_rndNo].endTime)
{
// finally award
if(round_m[_rndNo].leader == _playAddr)
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(60)/100);
}
//finally ten person award
for(uint256 i = 0;i < round_m[_rndNo].lastInfective.length; i = i.add(1))
{
if(round_m[_rndNo].lastInfective[i] == _playAddr && (round_m[_rndNo].totalInfective.sub(1) % 11) != i)
{
if(round_m[_rndNo].infectLastPlayer != address(0))
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(3)/100);
}
else{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(4)/100);
}
}
}
}
return
(
_ethPlayerAward,
_totalWithdraw,
playerRound_m[_rndNo][_playAddr].getInveterAmount,
playerRound_m[_rndNo][_playAddr].hasGetAwardAmount + playerRound_m[_rndNo][_playAddr].withdraw
);
}
/**
* @dev fee withdraw to receiver, everyone can do it.
* 0x6561e6ba
*/
function feeWithdraw()
onlyHuman()
public
{
require(isStartGame == true, "The game hasn't started yet.");
require(receiver != address(0), "The receiver address has not been initialized.");
uint256 _total = (totalEth.mul(5) / (100));
uint256 _withdrawed = ownerWithdraw;
require(_total > _withdrawed, "No need to withdraw");
ownerWithdraw = _total;
receiver.transfer(_total.sub(_withdrawed));
}
/**
* @dev start game
*/
function startGame()
onlyOwner()
public
{
round_m[1].startTime = now;
round_m[1].endTime = now + rndInfectiveStage_;
round_m[1].lastRoundReward = 0;
isStartGame = true;
}
/**
* @dev change owner.
*/
function changeReceiver(address newReceiver)
onlyOwner()
public
{
receiver = newReceiver;
}
/**
* @dev returns all current round info needed for front end
* 0x747dff42
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256[2], uint256[3], address[2], uint256[6], address[11],address[4])
{
require(isStartGame == true, "The game hasn't started yet.");
uint256 _rndNo = rndNo;
uint256 _totalAwardAtRound = round_m[_rndNo].lastRoundReward.add(round_m[_rndNo].exAward).add(round_m[_rndNo].eth.mul(30) / 100);
return (
_rndNo,
[round_m[_rndNo].eth, round_m[_rndNo].keys],
[round_m[_rndNo].startTime, round_m[_rndNo].endTime, round_m[_rndNo].infectiveEndTime],
[round_m[_rndNo].leader, round_m[_rndNo].infectLastPlayer],
[getBuyPrice(), round_m[_rndNo].lastRoundReward, _totalAwardAtRound, round_m[_rndNo].inveterAmount, round_m[_rndNo].totalInfective % 11, round_m[_rndNo].exAward],
round_m[_rndNo].lastInfective,
round_m[_rndNo].loseInfective
);
}
/**
* @dev return the price buyer will pay for next 1 individual key during first stage.
* 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
require(isStartGame == true, "The game hasn't started yet.");
uint256 _rndNo = rndNo;
uint256 _now = now;
// start next round?
if (_now > round_m[_rndNo].endTime)
{
return (750007031250000);
}
if (round_m[_rndNo].keys < allKeys_)
{
return ((round_m[_rndNo].keys.add(10000000000000000000)).ethRec(10000000000000000000));
}
if(round_m[_rndNo].keys >= allKeys_ &&
round_m[_rndNo].infectiveEndTime != 0 &&
round_m[_rndNo].infectLastPlayer != address(0) &&
_now < round_m[_rndNo].infectiveEndTime)
{
return 5 * 10 ** 16;
}
if(round_m[_rndNo].keys >= allKeys_ && _now > round_m[_rndNo].infectiveEndTime)
{
// increase 0.05 Ether every 3 hours
uint256 currentPrice = (((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(5 * 10 ** 16)).add((5 * 10 ** 16));
return currentPrice;
}
//second stage
return (0);
}
}
library KeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
|
returns all current round info needed for front end 0x747dff42/
|
function getCurrentRoundInfo()
public
view
returns(uint256, uint256[2], uint256[3], address[2], uint256[6], address[11],address[4])
{
require(isStartGame == true, "The game hasn't started yet.");
uint256 _rndNo = rndNo;
uint256 _totalAwardAtRound = round_m[_rndNo].lastRoundReward.add(round_m[_rndNo].exAward).add(round_m[_rndNo].eth.mul(30) / 100);
return (
_rndNo,
[round_m[_rndNo].eth, round_m[_rndNo].keys],
[round_m[_rndNo].startTime, round_m[_rndNo].endTime, round_m[_rndNo].infectiveEndTime],
[round_m[_rndNo].leader, round_m[_rndNo].infectLastPlayer],
[getBuyPrice(), round_m[_rndNo].lastRoundReward, _totalAwardAtRound, round_m[_rndNo].inveterAmount, round_m[_rndNo].totalInfective % 11, round_m[_rndNo].exAward],
round_m[_rndNo].lastInfective,
round_m[_rndNo].loseInfective
);
}
| 15,232,307 |
pragma solidity =0.6.6;
interface IDEXFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IDEXPair {
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 nonces(address owner) external view returns (uint);
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface ITradeSwap {
function factory() external pure returns (address);
function WBNB() 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 addLiquidityBNB(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountBNBMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountBNB, 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 removeLiquidityBNB(
address token,
uint liquidity,
uint amountTokenMin,
uint amountBNBMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountBNB);
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 swapExactBNBForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactBNB(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForBNB(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapBNBForExactTokens(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);
function removeLiquidityBNBSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountBNBMin,
address to,
uint deadline
) external returns (uint amountBNB);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactBNBForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForBNBSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IBEP20 {
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);
}
interface IWBNB {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract TradeSwap is ITradeSwap {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WBNB;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'TradeSwap: EXPIRED');
_;
}
constructor(address _factory, address _WBNB) public {
factory = _factory;
WBNB = _WBNB;
}
receive() external payable {
assert(msg.sender == WBNB); // only accept BNB via fallback from the WBNB 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 (IDEXFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IDEXFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'TradeSwap: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'TradeSwap: 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 = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IDEXPair(pair).mint(to);
}
function addLiquidityBNB(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountBNBMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountBNB, uint liquidity) {
(amountToken, amountBNB) = _addLiquidity(
token,
WBNB,
amountTokenDesired,
msg.value,
amountTokenMin,
amountBNBMin
);
address pair = UniswapV2Library.pairFor(factory, token, WBNB);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWBNB(WBNB).deposit{value: amountBNB}();
assert(IWBNB(WBNB).transfer(pair, amountBNB));
liquidity = IDEXPair(pair).mint(to);
// refund dust bnb, if any
if (msg.value > amountBNB) TransferHelper.safeTransferBNB(msg.sender, msg.value - amountBNB);
}
// **** 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 = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IDEXPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IDEXPair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'TradeSwap: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'TradeSwap: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityBNB(
address token,
uint liquidity,
uint amountTokenMin,
uint amountBNBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountBNB) {
(amountToken, amountBNB) = removeLiquidity(
token,
WBNB,
liquidity,
amountTokenMin,
amountBNBMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWBNB(WBNB).withdraw(amountBNB);
TransferHelper.safeTransferBNB(to, amountBNB);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityBNBSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountBNBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountBNB) {
(, amountBNB) = removeLiquidity(
token,
WBNB,
liquidity,
amountTokenMin,
amountBNBMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IBEP20(token).balanceOf(address(this)));
IWBNB(WBNB).withdraw(amountBNB);
TransferHelper.safeTransferBNB(to, amountBNB);
}
// **** 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,) = UniswapV2Library.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 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IDEXPair(UniswapV2Library.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 = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TradeSwap: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.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 = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TradeSwap: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactBNBForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WBNB, 'TradeSwap: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TradeSwap: INSUFFICIENT_OUTPUT_AMOUNT');
IWBNB(WBNB).deposit{value: amounts[0]}();
assert(IWBNB(WBNB).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactBNB(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] == WBNB, 'TradeSwap: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TradeSwap: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWBNB(WBNB).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferBNB(to, amounts[amounts.length - 1]);
}
function swapExactTokensForBNB(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] == WBNB, 'TradeSwap: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TradeSwap: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWBNB(WBNB).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferBNB(to, amounts[amounts.length - 1]);
}
function swapBNBForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WBNB, 'TradeSwap: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'TradeSwap: EXCESSIVE_INPUT_AMOUNT');
IWBNB(WBNB).deposit{value: amounts[0]}();
assert(IWBNB(WBNB).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust bnb, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferBNB(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,) = UniswapV2Library.sortTokens(input, output);
IDEXPair pair = IDEXPair(UniswapV2Library.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 = IBEP20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.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, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IBEP20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IBEP20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TradeSwap: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactBNBForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WBNB, 'TradeSwap: INVALID_PATH');
uint amountIn = msg.value;
IWBNB(WBNB).deposit{value: amountIn}();
assert(IWBNB(WBNB).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IBEP20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IBEP20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TradeSwap: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForBNBSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WBNB, 'TradeSwap: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IBEP20(WBNB).balanceOf(address(this));
require(amountOut >= amountOutMin, 'TradeSwap: INSUFFICIENT_OUTPUT_AMOUNT');
IWBNB(WBNB).withdraw(amountOut);
TransferHelper.safeTransferBNB(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
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');
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IDEXPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
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 safeTransferBNB(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: BNB_TRANSFER_FAILED');
}
}
|
refund dust bnb, if any
|
function swapBNBForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WBNB, 'TradeSwap: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'TradeSwap: EXCESSIVE_INPUT_AMOUNT');
assert(IWBNB(WBNB).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
if (msg.value > amounts[0]) TransferHelper.safeTransferBNB(msg.sender, msg.value - amounts[0]);
}
| 13,137,434 |
./full_match/77/0x24A8EB688BF52dE873E8d42144b1F84F0D9aC225/sources/contracts/Core.sol
|
Get condition by it's ID. conditionId the condition ID return the condition struct/
|
function getCondition(uint256 conditionId)
public
view
returns (Condition memory)
{
return _getCondition(conditionId);
}
| 5,046,859 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./ERC20Factory.sol";
/// @title NFT Fractionalizer with Buyout Functionality
/// @author Web3Wannabe
/// @notice NFTs can be sent to the contract with a specified buyout price. The sender receives the total supply of a newly created ERC20 token.
contract FractionalizeNFT is IERC721Receiver {
using Counters for Counters.Counter;
Counters.Counter private _fracNFTCount;
mapping(uint256 => FractionalizedNFT) public fracNFTs; // A mapping of all fractionalized NFTs.
struct FractionalizedNFT {
uint256 fracNFTId;
uint256 nftTokenId;
address erc721Address;
address erc20Address;
string erc20Symbol;
string erc20Name;
address payable originalOwner;
uint256 buyoutPrice;
State state;
}
enum State {
Fractionalized,
Redeemed,
BoughtOut
}
constructor() {}
/// @notice Emitted when ether is sent to the contract.
/// @param sender The sender of the transaction/ether.
/// @param value The amount of ether sent.
event Received(address indexed sender, uint256 indexed value);
/// @notice Emitted when an NFT is transferred to the FractionalizeNFT contract.
/// @param sender The address that sent the NFT.
event NftReceived(address indexed sender);
/// @notice Emitted when a user successfully fractionalizes an NFT and receives the total supply of the newly created ERC20 token.
/// @param sender The address that sent/fractionalized the NFT (i.e., the address that called fractionalize()).
/// @param fracNFTId The ID of the newly fractionalized NFT.
/// @param erc20Name The name of the newly created ERC20 token.
/// @param erc20Address The contract address of the newly created ERC20 token.
event Fractionalized(
address indexed sender,
uint256 indexed fracNFTId,
string indexed erc20Name,
address erc20Address
);
/// @notice Emitted when a user successfully redeems an NFT in exchange for the total ERC20 supply.
/// @param sender The address that redeemed the NFT (i.e., the address that called redeem()).
/// @param fracNFTId The index of the fractionalized NFT that was redeemed.
event Redeemed(address indexed sender, uint256 indexed fracNFTId);
/// @notice Emitted when a user successfully claims a payout following the buyout of an NFT from the FractionalizeNFT contract.
/// @param sender The address that the user held ERC20 tokens for (i.e., the address that called claim()).
/// @param fracNFTId The index of the fractionalized NFT that was bought.
event Claimed(address indexed sender, uint256 indexed fracNFTId);
/// @notice Emitted when a user successfully buys an NFT from the FractionalizeNFT contract.
/// @param sender The address that bought the NFT (i.e., the address that called buyout()).
/// @param fracNFTId The index of the fractionalized NFT that was bought.
event BoughtOut(address indexed sender, uint256 indexed fracNFTId);
modifier isLegalFracNftId(uint256 fracNFTId) {
require(
fracNFTId < _fracNFTCount.current(),
"fracNFTId does not exist in fracNFTs."
);
_;
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
fallback() external payable {
revert();
}
/// @notice A getter function to get the current number of fractionalized NFT entries in the contract.
/// @return The number of fractionalized NFT entries.
function getFracNftCount() public view returns (uint256) {
return _fracNFTCount.current();
}
/// @notice A getter function for the contract address of a fractionalized NFT's ERC20 token.
/// @param fracNFTId The ID of the fractionalized NFT.
/// @return The ERC20 contract address.
function getERC20Address(uint256 fracNFTId)
public
view
isLegalFracNftId(fracNFTId)
returns (address)
{
return fracNFTs[fracNFTId].erc20Address;
}
/// @notice A getter function for the symbol of a fractionalized NFT's ERC20 token.
/// @param fracNFTId The ID of the fractionalized NFT.
/// @return The ERC20's symobl.
function getERC20Symbol(uint256 fracNFTId)
public
view
isLegalFracNftId(fracNFTId)
returns (string memory)
{
return fracNFTs[fracNFTId].erc20Symbol;
}
/// @notice A getter function for the state of a fractionalized NFT.
/// @param fracNFTId The ID of the fractionalized NFT.
/// @return The fractionalized NFT's state (Fractionalized, Redeemed or BoughtOut).
function getState(uint256 fracNFTId)
public
view
isLegalFracNftId(fracNFTId)
returns (State)
{
return fracNFTs[fracNFTId].state;
}
/// @notice Create a fractionalized NFT: Lock the NFT in the contract; create a new ERC20 token, as specified; and transfer the total supply of the token to the sender.
/// @param nftContractAddress The address of the NFT that is to be fractionalized.
/// @param nftTokenId The token ID of the NFT that is to be fractionalized.
/// @param erc20Name The name of the newly created ERC20 token.
/// @param erc20Symbol The symbol of the newly created ERC20 token.
/// @param erc20Supply The total supply of the newly created ERC20 token.
/// @param buyoutPrice The price (in Wei) for which the fractionalized NFT can be be bought for from the contract.
/// @dev Note, the NFT must be approved for transfer by the FractionalizeNFT contract.
/// @return The ID of the newly created fractionalized NFT.
function fractionalizeNft(
address nftContractAddress,
uint256 nftTokenId,
string memory erc20Name,
string memory erc20Symbol,
uint256 erc20Supply,
uint256 buyoutPrice
) public returns (uint256) {
ERC20 erc20 = (new ERC20Factory)(
erc20Name,
erc20Symbol,
erc20Supply,
msg.sender
);
uint256 fracNFTId = _fracNFTCount.current();
fracNFTs[_fracNFTCount.current()] = FractionalizedNFT({
fracNFTId: fracNFTId,
nftTokenId: nftTokenId,
erc721Address: nftContractAddress,
erc20Address: address(erc20),
erc20Symbol: erc20Symbol,
erc20Name: erc20Name,
originalOwner: payable(msg.sender),
buyoutPrice: buyoutPrice,
state: State.Fractionalized
});
_fracNFTCount.increment();
ERC721 nft = ERC721(nftContractAddress);
nft.safeTransferFrom(msg.sender, address(this), nftTokenId);
emit Fractionalized(msg.sender, fracNFTId, erc20Symbol, address(erc20));
return fracNFTId;
}
/// @notice A holder of the entire ERC20 supply can call redeem in order to receive the underlying NFT from the contract. The ERC20 tokens get transferred to the contract address.
/// @param fracNFTId The ID of the fractionalized NFT to redem.
/// @dev Note, the ERC20 must be approved for transfer by the FractionalizeNFT contract before calling redeem().
function redeem(uint256 fracNFTId) public {
ERC20 erc20 = ERC20(fracNFTs[fracNFTId].erc20Address);
uint256 redeemerBalance = erc20.balanceOf(msg.sender);
uint256 erc20Supply = erc20.totalSupply();
require(
redeemerBalance == erc20Supply,
"Redeemeer does not hold the entire supply."
);
fracNFTs[fracNFTId].state = State.Redeemed;
erc20.transferFrom(msg.sender, address(this), redeemerBalance);
ERC721 erc721 = ERC721(fracNFTs[fracNFTId].erc721Address);
erc721.safeTransferFrom(
address(this),
msg.sender,
fracNFTs[fracNFTId].nftTokenId
);
emit Redeemed(msg.sender, fracNFTId);
}
/// @notice Allows a holder of the ERC20 tokens to claim his share of the sale proceedings (in ether) following a buyout of the fractionalized NFT.
/// @param fracNFTId The ID of the fractionalized NFT to claim a payout for.
/// @dev Note, the ERC20 must be approved for transfer by the FractionalizeNFT contract before calling claim().
function claim(uint256 fracNFTId) public {
require(
fracNFTs[fracNFTId].state == State.BoughtOut,
"Fractionalized NFT has not been bought out."
);
ERC20 erc20 = ERC20(fracNFTs[fracNFTId].erc20Address);
uint256 claimerBalance = erc20.balanceOf(msg.sender);
require(claimerBalance > 0, "Claimer does not hold any tokens.");
erc20.transferFrom(msg.sender, address(this), claimerBalance);
uint256 erc20Supply = erc20.totalSupply();
uint256 claimAmountWei = (fracNFTs[fracNFTId].buyoutPrice *
claimerBalance) / erc20Supply;
payable(msg.sender).transfer(claimAmountWei);
emit Claimed(msg.sender, fracNFTId);
}
/// @notice Allows an account to buy the NFT from the contract for the specified buyout price.
/// @param fracNFTId The ID of the fractionalized NFT to buy.
function buyout(uint256 fracNFTId) public payable {
// A buyer can buy the NFT as specified by the buyout price by sending ETH to the contract.
require(
msg.value >= fracNFTs[fracNFTId].buyoutPrice,
"Sender sent less than the buyout price."
);
fracNFTs[fracNFTId].state = State.BoughtOut;
ERC721 erc721 = ERC721(fracNFTs[fracNFTId].erc721Address);
erc721.safeTransferFrom(
address(this),
msg.sender,
fracNFTs[fracNFTId].nftTokenId
);
emit BoughtOut(msg.sender, fracNFTId);
}
/// @dev Required to use safeTransferFrom() from OpenZeppelin's ERC721 contract (when transferring NFTs to this contract).
function onERC721Received(
address operator,
address from,
uint256 nftTokenId,
bytes memory data
) public returns (bytes4) {
emit NftReceived(msg.sender);
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
}
|
A getter function to get the current number of fractionalized NFT entries in the contract. return The number of fractionalized NFT entries.
|
function getFracNftCount() public view returns (uint256) {
return _fracNFTCount.current();
}
| 13,081,366 |
./full_match/5/0xb89B22b1F0e5513B69737873D97Be5AF93A36f83/sources/project_/contracts/ERC721Soulbound.sol
|
Mints a new Soulbound token to multiple recipients This function is restricted to the creator admin./
|
function mintTokens(address creatorContractAddress, address[] memory recipients, string memory tokenURI) external creatorAdminRequired(creatorContractAddress) {
require(recipients.length > 0 && recipients.length <= 10, "1-10 recipients allowed");
for (uint i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Invalid recipient address");
uint256 tokenId = IERC721CreatorCore(creatorContractAddress).mintExtension(recipients[i], tokenURI);
tokenIdIsSoulbound[creatorContractAddress][tokenId] = true;
if (!isSoulboundOwner[creatorContractAddress][recipients[i]]) {
soulboundOwners[creatorContractAddress].push(recipients[i]);
isSoulboundOwner[creatorContractAddress][recipients[i]] = true;
}
emit SoulboundTokenMinted(creatorContractAddress, recipients[i], tokenId);
}
}
| 7,063,673 |
./full_match/80001/0x38CeA9014C05c5d6887C86247a3F73483D97D421/sources/contracts/funds/FsmDevFund.sol
|
===================== VIEWS =====================/
|
function allocation() public pure override returns (uint256) {
return ALLOCATION;
}
| 843,932 |
./partial_match/42/0xD5B34Ceab314cDAe37A90897B61aeD755e0b2CF0/sources/Depot.sol
|
Calculate how many PERI you will receive if you transfer an amount of Pynths. amount The amount of Pynths (in 18 decimal places) you want to ask about/ And what would that be worth in PERI based on the current price?
|
function PynthetixReceivedForPynths(uint amount) public view returns (uint) {
return amount.divideDecimal(exchangeRates().rateForCurrency(PERI));
}
| 3,342,796 |
./full_match/44787/0xAD63F69c2BaE2B6E1A83d2Ec4dd4de551a5C501F/sources/contracts/Snippool.sol
|
the password is "forever"
|
function lockRoyaltyEnforcement(string memory password) external onlyOwner {
if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
revert WrongPassword();
}
options.royaltyEnforcementLocked = true;
}
| 13,249,061 |
pragma solidity 0.5.6;
library SafeMath {
function MUL223(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV41(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB337(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD232(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD295(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract ERC20Interface {
function TOTALSUPPLY507() public view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF692(address tokenOwner) public view returns (uint balance); //inject NONSTANDARD NAMING
function ALLOWANCE171(address tokenOwner, address spender) public view returns (uint remaining); //inject NONSTANDARD NAMING
function TRANSFER863(address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING
function APPROVE857(address spender, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM994(address from, address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING
uint8 public decimals;
event TRANSFER332(address indexed from, address indexed to, uint tokens); //inject NONSTANDARD NAMING
event APPROVAL437(address indexed tokenOwner, address indexed spender, uint tokens); //inject NONSTANDARD NAMING
}
contract DAIHardFactory {
event NEWTRADE364(uint id, address tradeAddress, bool indexed initiatorIsPayer); //inject NONSTANDARD NAMING
ERC20Interface public daiContract;
address payable public devFeeAddress;
constructor(ERC20Interface _daiContract, address payable _devFeeAddress)
public {
daiContract = _daiContract;
devFeeAddress = _devFeeAddress;
}
struct CreationInfo {
address address_;
uint blocknum;
}
CreationInfo[] public createdTrades;
function GETBUYERDEPOSIT760(uint tradeAmount) //inject NONSTANDARD NAMING
public
pure
returns (uint buyerDeposit) {
return tradeAmount / 3;
}
function GETDEVFEE266(uint tradeAmount) //inject NONSTANDARD NAMING
public
pure
returns (uint devFee) {
return tradeAmount / 100;
}
function GETEXTRAFEES516(uint tradeAmount) //inject NONSTANDARD NAMING
public
pure
returns (uint buyerDeposit, uint devFee) {
return (GETBUYERDEPOSIT760(tradeAmount), GETDEVFEE266(tradeAmount));
}
function OPENDAIHARDTRADE782(address payable _initiator, bool initiatorIsBuyer, uint[5] calldata uintArgs, string calldata _totalPrice, string calldata _fiatTransferMethods, string calldata _commPubkey) //inject NONSTANDARD NAMING
external
returns (DAIHardTrade) {
uint transferAmount;
uint[6] memory newUintArgs; // Note that this structure is not the same as the above comment describes. See below in DAIHardTrade.open.
if (initiatorIsBuyer) {
//transferAmount = getBuyerDeposit(uintArgs[0]) + uintArgs[1] + getDevFee(uintArgs[0]); (kept for legibility; SafeMath must be used)
transferAmount = SafeMath.ADD232(SafeMath.ADD232(GETBUYERDEPOSIT760(uintArgs[0]), uintArgs[1]), GETDEVFEE266(uintArgs[0]));
newUintArgs = [uintArgs[0], uintArgs[1], GETDEVFEE266(uintArgs[0]), uintArgs[2], uintArgs[3], uintArgs[4]];
}
else {
//transferAmount = uintArgs[0] + uintArgs[1] + getDevFee(uintArgs[0]); (kept for legibility; SafeMath must be used)
transferAmount = SafeMath.ADD232(SafeMath.ADD232(uintArgs[0], uintArgs[1]), GETDEVFEE266(uintArgs[0]));
newUintArgs = [GETBUYERDEPOSIT760(uintArgs[0]), uintArgs[1], GETDEVFEE266(uintArgs[0]), uintArgs[2], uintArgs[3], uintArgs[4]];
}
//create the new trade and add its creationInfo to createdTrades
DAIHardTrade newTrade = new DAIHardTrade(daiContract, devFeeAddress);
createdTrades.push(CreationInfo(address(newTrade), block.number));
emit NEWTRADE364(createdTrades.length - 1, address(newTrade), initiatorIsBuyer);
//transfer DAI to the trade and open it
require(daiContract.TRANSFERFROM994(msg.sender, address(newTrade), transferAmount), "Token transfer failed. Did you call approve() on the DAI contract?");
newTrade.OPEN777(_initiator, initiatorIsBuyer, newUintArgs, _totalPrice, _fiatTransferMethods, _commPubkey);
}
function GETNUMTRADES43() //inject NONSTANDARD NAMING
external
view
returns (uint num) {
return createdTrades.length;
}
}
contract DAIHardTrade {
enum Phase {Created, Open, Committed, Claimed, Closed}
Phase public phase;
modifier INPHASE268(Phase p) { //inject NONSTANDARD NAMING
require(phase == p, "inPhase check failed.");
_;
}
uint[5] public phaseStartTimestamps;
function CHANGEPHASE108(Phase p) //inject NONSTANDARD NAMING
internal {
phase = p;
phaseStartTimestamps[uint(p)] = block.timestamp;
}
address payable public initiator;
address payable public responder;
//The contract only has two parties, but depending on how it's opened,
//the initiator for example might be either the buyer OR the seller.
bool public initiatorIsBuyer;
address payable public buyer;
address payable public seller;
modifier ONLYINITIATOR28() { //inject NONSTANDARD NAMING
require(msg.sender == initiator, "msg.sender is not Initiator.");
_;
}
modifier ONLYRESPONDER481() { //inject NONSTANDARD NAMING
require(msg.sender == responder, "msg.sender is not Responder.");
_;
}
modifier ONLYBUYER57() { //inject NONSTANDARD NAMING
require (msg.sender == buyer, "msg.sender is not Buyer.");
_;
}
modifier ONLYSELLER716() { //inject NONSTANDARD NAMING
require (msg.sender == seller, "msg.sender is not Seller.");
_;
}
modifier ONLYCONTRACTPARTY42() { // Must be one of the two parties involved in the contract //inject NONSTANDARD NAMING
require(msg.sender == initiator || msg.sender == responder, "msg.sender is not a party in this contract.");
_;
}
ERC20Interface daiContract;
address payable devFeeAddress;
constructor(ERC20Interface _daiContract, address payable _devFeeAddress)
public {
CHANGEPHASE108(Phase.Created);
daiContract = _daiContract;
devFeeAddress = _devFeeAddress;
pokeRewardSent = false;
}
uint public daiAmount;
string public price;
uint public buyerDeposit;
uint public responderDeposit; // This will be equal to either daiAmount or buyerDeposit, depending on initiatorIsBuyer
uint public autorecallInterval;
uint public autoabortInterval;
uint public autoreleaseInterval;
uint public pokeReward;
uint public devFee;
bool public pokeRewardSent;
event OPENED397(string fiatTransferMethods, string commPubkey); //inject NONSTANDARD NAMING
function OPEN777(address payable _initiator, bool _initiatorIsBuyer, uint[6] memory uintArgs, string memory _price, string memory fiatTransferMethods, string memory commPubkey) //inject NONSTANDARD NAMING
public
INPHASE268(Phase.Created) {
require(GETBALANCE315() > 0, "You can't open a trade without first depositing DAI.");
responderDeposit = uintArgs[0];
pokeReward = uintArgs[1];
devFee = uintArgs[2];
autorecallInterval = uintArgs[3];
autoabortInterval = uintArgs[4];
autoreleaseInterval = uintArgs[5];
initiator = _initiator;
initiatorIsBuyer = _initiatorIsBuyer;
if (initiatorIsBuyer) {
buyer = initiator;
daiAmount = responderDeposit;
buyerDeposit = SafeMath.SUB337(GETBALANCE315(), SafeMath.ADD232(pokeReward, devFee));
}
else {
seller = initiator;
daiAmount = SafeMath.SUB337(GETBALANCE315(), SafeMath.ADD232(pokeReward, devFee));
buyerDeposit = responderDeposit;
}
price = _price;
CHANGEPHASE108(Phase.Open);
emit OPENED397(fiatTransferMethods, commPubkey);
}
event RECALLED650(); //inject NONSTANDARD NAMING
event COMMITTED568(address responder, string commPubkey); //inject NONSTANDARD NAMING
function RECALL905() //inject NONSTANDARD NAMING
external
INPHASE268(Phase.Open)
ONLYINITIATOR28() {
INTERNALRECALL236();
}
function INTERNALRECALL236() //inject NONSTANDARD NAMING
internal {
require(daiContract.TRANSFER863(initiator, GETBALANCE315()), "Recall of DAI to initiator failed!");
CHANGEPHASE108(Phase.Closed);
emit RECALLED650();
}
function AUTORECALLAVAILABLE89() //inject NONSTANDARD NAMING
public
view
INPHASE268(Phase.Open)
returns(bool available) {
return (block.timestamp >= SafeMath.ADD232(phaseStartTimestamps[uint(Phase.Open)], autorecallInterval));
}
function COMMIT855(string calldata commPubkey) //inject NONSTANDARD NAMING
external
INPHASE268(Phase.Open) {
require(daiContract.TRANSFERFROM994(msg.sender, address(this), responderDeposit), "Can't transfer the required deposit from the DAI contract. Did you call approve first?");
require(!AUTORECALLAVAILABLE89(), "autorecallInterval has passed; this offer has expired.");
responder = msg.sender;
if (initiatorIsBuyer) {
seller = responder;
}
else {
buyer = responder;
}
CHANGEPHASE108(Phase.Committed);
emit COMMITTED568(responder, commPubkey);
}
event CLAIMED907(); //inject NONSTANDARD NAMING
event ABORTED68(); //inject NONSTANDARD NAMING
function ABORT91() //inject NONSTANDARD NAMING
external
INPHASE268(Phase.Committed)
ONLYBUYER57() {
INTERNALABORT901();
}
function INTERNALABORT901() //inject NONSTANDARD NAMING
internal {
//Punishment amount is 1/4 the buyerDeposit for now,
//but in a future version this might be set by the Initiator.
uint burnAmount = buyerDeposit / 4;
//Punish both parties equally by burning burnAmount.
//Instead of burning burnAmount twice, just burn it all in one call (saves gas).
require(daiContract.TRANSFER863(address(0x0), burnAmount*2), "Token burn failed!");
//Send back deposits minus burned amounts.
require(daiContract.TRANSFER863(buyer, SafeMath.SUB337(buyerDeposit, burnAmount)), "Token transfer to Buyer failed!");
require(daiContract.TRANSFER863(seller, SafeMath.SUB337(daiAmount, burnAmount)), "Token transfer to Seller failed!");
uint sendBackToInitiator = devFee;
//If there was a pokeReward left, it should be sent back to the initiator
if (!pokeRewardSent) {
sendBackToInitiator = SafeMath.ADD232(sendBackToInitiator, pokeReward);
}
require(daiContract.TRANSFER863(initiator, sendBackToInitiator), "Token refund of devFee+pokeReward to Initiator failed!");
//There may be a wei or two left over in the contract due to integer division. Not a big deal.
CHANGEPHASE108(Phase.Closed);
emit ABORTED68();
}
function AUTOABORTAVAILABLE128() //inject NONSTANDARD NAMING
public
view
INPHASE268(Phase.Committed)
returns(bool passed) {
return (block.timestamp >= SafeMath.ADD232(phaseStartTimestamps[uint(Phase.Committed)], autoabortInterval));
}
function CLAIM992() //inject NONSTANDARD NAMING
external
INPHASE268(Phase.Committed)
ONLYBUYER57() {
require(!AUTOABORTAVAILABLE128(), "The deposit deadline has passed!");
CHANGEPHASE108(Phase.Claimed);
emit CLAIMED907();
}
event RELEASED940(); //inject NONSTANDARD NAMING
event BURNED656(); //inject NONSTANDARD NAMING
function AUTORELEASEAVAILABLE963() //inject NONSTANDARD NAMING
public
view
INPHASE268(Phase.Claimed)
returns(bool available) {
return (block.timestamp >= SafeMath.ADD232(phaseStartTimestamps[uint(Phase.Claimed)], autoreleaseInterval));
}
function RELEASE38() //inject NONSTANDARD NAMING
external
INPHASE268(Phase.Claimed)
ONLYSELLER716() {
INTERNALRELEASE836();
}
function INTERNALRELEASE836() //inject NONSTANDARD NAMING
internal {
//If the pokeReward has not been sent, refund it to the initiator
if (!pokeRewardSent) {
require(daiContract.TRANSFER863(initiator, pokeReward), "Refund of pokeReward to Initiator failed!");
}
//Upon successful resolution of trade, the devFee is sent to the developers of DAIHard.
require(daiContract.TRANSFER863(devFeeAddress, devFee), "Token transfer to devFeeAddress failed!");
//Release the remaining balance to the buyer.
require(daiContract.TRANSFER863(buyer, GETBALANCE315()), "Final release transfer to buyer failed!");
CHANGEPHASE108(Phase.Closed);
emit RELEASED940();
}
function BURN989() //inject NONSTANDARD NAMING
external
INPHASE268(Phase.Claimed)
ONLYSELLER716() {
require(!AUTORELEASEAVAILABLE963());
INTERNALBURN180();
}
function INTERNALBURN180() //inject NONSTANDARD NAMING
internal {
require(daiContract.TRANSFER863(address(0x0), GETBALANCE315()), "Final DAI burn failed!");
CHANGEPHASE108(Phase.Closed);
emit BURNED656();
}
function GETSTATE363() //inject NONSTANDARD NAMING
external
view
returns(uint balance, Phase phase, uint phaseStartTimestamp, address responder) {
return (GETBALANCE315(), this.phase(), phaseStartTimestamps[uint(this.phase())], this.responder());
}
function GETBALANCE315() //inject NONSTANDARD NAMING
public
view
returns(uint) {
return daiContract.BALANCEOF692(address(this));
}
function GETPARAMETERS67() //inject NONSTANDARD NAMING
external
view
returns (address initiator, bool initiatorIsBuyer, uint daiAmount, string memory totalPrice, uint buyerDeposit, uint autorecallInterval, uint autoabortInterval, uint autoreleaseInterval, uint pokeReward)
{
return (this.initiator(), this.initiatorIsBuyer(), this.daiAmount(), this.price(), this.buyerDeposit(), this.autorecallInterval(), this.autoabortInterval(), this.autoreleaseInterval(), this.pokeReward());
}
// Poke function lets anyone move the contract along,
// if it's due for some state transition.
event POKE500(); //inject NONSTANDARD NAMING
function POKENEEDED61() //inject NONSTANDARD NAMING
public
view
returns (bool needed) {
return ( (phase == Phase.Open && AUTORECALLAVAILABLE89() )
|| (phase == Phase.Committed && AUTOABORTAVAILABLE128() )
|| (phase == Phase.Claimed && AUTORELEASEAVAILABLE963())
);
}
function POKE367() //inject NONSTANDARD NAMING
external
returns (bool moved) {
if (POKENEEDED61()) {
daiContract.TRANSFER863(msg.sender, pokeReward);
pokeRewardSent = true;
emit POKE500();
}
else return false;
if (phase == Phase.Open) {
if (AUTORECALLAVAILABLE89()) {
INTERNALRECALL236();
return true;
}
}
else if (phase == Phase.Committed) {
if (AUTOABORTAVAILABLE128()) {
INTERNALABORT901();
return true;
}
}
else if (phase == Phase.Claimed) {
if (AUTORELEASEAVAILABLE963()) {
INTERNALRELEASE836();
return true;
}
}
}
// StatementLogs allow a starting point for any necessary communication,
// and can be used anytime by either party after a Responder commits (even in the Closed phase).
event INITIATORSTATEMENTLOG161(string encryptedForInitiator, string encryptedForResponder); //inject NONSTANDARD NAMING
event RESPONDERSTATEMENTLOG369(string encryptedForInitiator, string encryptedForResponder); //inject NONSTANDARD NAMING
function INITIATORSTATEMENT924(string memory encryptedForInitiator, string memory encryptedForResponder) //inject NONSTANDARD NAMING
public
ONLYINITIATOR28() {
require(phase >= Phase.Committed);
emit INITIATORSTATEMENTLOG161(encryptedForInitiator, encryptedForResponder);
}
function RESPONDERSTATEMENT364(string memory encryptedForInitiator, string memory encryptedForResponder) //inject NONSTANDARD NAMING
public
ONLYRESPONDER481() {
require(phase >= Phase.Committed);
emit RESPONDERSTATEMENTLOG369(encryptedForInitiator, encryptedForResponder);
}
}
|
inject NONSTANDARD NAMING
|
function SUB337(uint256 a, uint256 b) internal pure returns (uint256) {
| 5,369,330 |
pragma solidity 0.4.24;
// _____________________________________________________________
// .''
// ._.-.___.' (`\
// //( ( `'
// '/ )\ ).__. )
// ' <' `\ ._/'\
// ________`___\_____\__________________________________________
// .''
// ___ _____ _ __ ___ ___ ._.-.___.' (`\
// / _//_ _//// // _/ / o | //( ( `'
// / _/ / / / ` // _/ / ,' '/ )\ ).__. )
// /___/ /_/ /_n_//___//_/`_\ ' <' `\ ._/'\
// __________________________________`___\_____\________________
// .''
// __ ___ ___ ___ _ __ ._.-.___.' (`\
// / \ / _/ / o | / o.)| |/,' //( ( `'
// / o |/ _/ / ,' / o \ | ,' '/ )\ ).__. )
// /__,'/___//_/`_\/___,'/_/ ' <' `\ ._/'\
// __________________________________________`___\_____\________
// .''
// ._.-.___.' (`\
// //( ( `'
// '/ )\ ).__. )
// ' <' `\ ._/'\
// __________________`___\_____\________________________________
//
// This product is protected under license. Any unauthorized copy, modification, or use without
// express written consent from the creators is prohibited.
//
contract EtherDerby {
using SafeMath for *;
using CalcCarrots for uint256;
// settings
string constant public name = "EtherDerby";
uint256 constant private ROUNDMAX = 4 hours;
uint256 constant private MULTIPLIER = 2**64;
uint256 constant private DECIMALS = 18;
uint256 constant public REGISTERFEE = 20 finney;
address constant private DEVADDR = 0xC17A40cB38598520bd7C0D5BFF97D441A810a008;
// horse Identifiers
uint8 constant private H1 = 1;
uint8 constant private H2 = 2;
uint8 constant private H3 = 3;
uint8 constant private H4 = 4;
// ___ _ _ ___ __ _ ___ _
// |_ _|| U || __| | \ / \|_ _|/ \
// | | | || _| | o ) o || || o |
// |_| |_n_||___| |__/|_n_||_||_n_|
//
struct Round {
uint8 winner; // horse in the lead
mapping (uint8 => uint256) eth; // total eth per horse
mapping (uint8 => uint256) carrots; // total eth per horse
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 totalWinnings; // player winnings
uint256 totalReferrals; // player referral bonuses
int256 dividendPayouts; // running count of payouts player has received (important that it can be negative)
mapping (uint256 => mapping (uint8 => uint256)) eth; // round -> horse -> eTH invested
mapping (uint256 => mapping (uint8 => uint256)) carrots; // round -> horse -> carrots purchased
mapping (uint256 => mapping (uint8 => uint256)) referrals; // round -> horse -> referrals (eth)
mapping (uint8 => uint256) totalEth; // total carrots invested in each horse by the player
mapping (uint8 => uint256) totalCarrots; // total carrots invested in each horse by the player
uint256 totalWithdrawn; // running total of ETH withdrawn by the player
uint256 totalReinvested; // running total of ETH reinvested by the player
uint256 roundLastManaged; // round players winnings were last recorded
uint256 roundLastReferred; // round player was last referred and therefore had its referrals managed
address lastRef; // address of player who last referred this player
}
struct Horse {
bytes32 name;
uint256 totalEth;
uint256 totalCarrots;
uint256 mostCarrotsOwned;
address owner;
}
uint256 rID_ = 0; // current round number
mapping (uint256 => Round) public rounds_; // data for each round
uint256 roundEnds_; // time current round is over
mapping (address => Player) public players_; // data for each player
mapping (uint8 => Horse) horses_; // data for each horse
uint256 private earningsPerCarrot_; // used to keep track of dividends rewarded to carrot holders
mapping (bytes32 => address) registeredNames_;
// ___ _ _ ___ _ _ ___ __
// | __|| | || __|| \| ||_ _/ _|
// | _| | V || _| | \\ | | |\_ \
// |___| \_/ |___||_|\_| |_||__/
//
/**
* @dev fired for every set of carrots purchased or reinvested in
* @param playerAddress player making the purchase
* @param playerName players name if they have registered
* @param roundId round for which carrots were purchased
* @param horse array of two horses (stack limit hit so we use array)
* 0 - horse which horse carrots were purchased for
* 1 - horse now in the lead
* @param horseName horse name at the time of purchase
* @param roundEnds round end time
* @param timestamp block timestamp when purchase occurred
* @param data contains the following (stack limit hit so we use array)
* 0 - amount of eth
* 1 - amount of carrots
* 2 - horses total eth for the round
* 3 - horses total carrots for the round
* 4 - players total eth for the round
* 5 - players total carrots for the round
*/
event OnCarrotsPurchased
(
address indexed playerAddress,
bytes32 playerName,
uint256 roundId,
uint8[2] horse,
bytes32 indexed horseName,
uint256[6] data,
uint256 roundEnds,
uint256 timestamp
);
/**
* @dev fired each time a player withdraws ETH
* @param playerAddress players address
* @param eth amount withdrawn
*/
event OnEthWithdrawn
(
address indexed playerAddress,
uint256 eth
);
/**
* @dev fired whenever a horse is given a new name
* @param playerAddress which player named the horse
* @param horse number of horse being named
* @param horseName new name of horse
* @param mostCarrotsOwned number of carrots by owned to name the horse
* @param timestamp block timestamp when horse is named
*/
event OnHorseNamed
(
address playerAddress,
bytes32 playerName,
uint8 horse,
bytes32 horseName,
uint256 mostCarrotsOwned,
uint256 timestamp
);
/**
* @dev fired whenever a player registers a name
* @param playerAddress which player registered a name
* @param playerName name being registered
* @param ethDonated amount of eth donated with registration
* @param timestamp block timestamp when name registered
*/
event OnNameRegistered
(
address playerAddress,
bytes32 playerName,
uint256 ethDonated,
uint256 timestamp
);
/**
* @dev fired when a transaction is rejected
* mainly used to make it easier to write front end code
* @param playerAddress player making the purchase
* @param reason why the transaction failed
*/
event OnTransactionFail
(
address indexed playerAddress,
bytes32 reason
);
constructor()
public
{
// start with Round 0 ending before now so that first purchase begins Round 1
// subtract an hour to make sure the first purchase doesn't go to round 0 (ex. same block)
roundEnds_ = block.timestamp - 1 hours;
// default horse names
horses_[H1].name = "horse1";
horses_[H2].name = "horse2";
horses_[H3].name = "horse3";
horses_[H4].name = "horse4";
}
// _ _ _ __ _ ___ _ ___ ___ __
// | \_/ |/ \| \| || __|| || __|| o \/ _|
// | \_/ ( o ) o ) || _| | || _| | /\_ \
// |_| |_|\_/|__/|_||_| |_||___||_|\\|__/
//
/**
* @dev verifies that a valid horse is provided
*/
modifier isValidHorse(uint8 _horse) {
require(_horse == H1 || _horse == H2 || _horse == H3 || _horse == H4, "unknown horse selected");
_;
}
/**
* @dev prevents smart contracts from interacting with EtherDerby
*/
modifier isHuman() {
address addr = msg.sender;
uint256 codeLength;
assembly {codeLength := extcodesize(addr)}
require(codeLength == 0, "Humans only ;)");
require(msg.sender == tx.origin, "Humans only ;)");
_;
}
/**
* @dev verifies that all purchases sent include a reasonable amount of ETH
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "Not enough eth!");
require(_eth <= 100000000000000000000000, "Go away whale!");
_;
}
// ___ _ _ ___ _ _ __ ___ _ _ _ _ __ ___ _ _ _ _ __
// | o \ | || o ) | | |/ _| | __|| | || \| |/ _||_ _|| |/ \| \| |/ _|
// | _/ U || o \ |_ | ( (_ | _| | U || \\ ( (_ | | | ( o ) \\ |\_ \
// |_| |___||___/___||_|\__| |_| |___||_|\_|\__| |_| |_|\_/|_|\_||__/
//
/**
* @dev register a name with Ether Derby to generate a referral link
* @param _nameStr the name being registered (see NameValidator library below
* for name requirements)
*/
function registerName(string _nameStr)
public
payable
isHuman()
{
require(msg.value >= REGISTERFEE, "You must pay the partner fee of 20 finney");
bytes32 nameToRegister = NameValidator.validate(_nameStr);
require(registeredNames_[nameToRegister] == 0, "Name already in use");
registeredNames_[nameToRegister] = msg.sender;
players_[msg.sender].name = nameToRegister;
// partner fee goes to devs
players_[DEVADDR].totalReferrals = msg.value.add(players_[DEVADDR].totalReferrals);
emit OnNameRegistered(msg.sender, nameToRegister, msg.value, block.timestamp);
}
/**
* @dev buy carrots with ETH
* @param _horse the horse carrots are being purchased for
* @param _round the round these carrots should be purchased for (send 0 to
* buy for whatever the current round is)
* @param _referrerName the player for which to reward referral bonuses to
*/
function buyCarrots(uint8 _horse, uint256 _round, bytes32 _referrerName)
public
payable
isHuman()
isWithinLimits(msg.value)
isValidHorse(_horse)
{
if (isInvalidRound(_round)) {
emit OnTransactionFail(msg.sender, "Invalid round");
msg.sender.transfer(msg.value);
return;
}
buyCarrotsInternal(_horse, msg.value, _referrerName);
}
/**
* @dev buy carrots with current earnings left in smart contract
* @param _horse the horse carrots are being purchased for
* @param _round the round these carrots should be purchased for (send 0 to
* buy for whatever the current round is)
* @param _referrerName the player for which to reward referral bonuses to
*/
function reinvestInCarrots(uint8 _horse, uint256 _round, uint256 _value, bytes32 _referrerName)
public
isHuman()
isWithinLimits(_value)
isValidHorse(_horse)
{
if (isInvalidRound(_round)) {
emit OnTransactionFail(msg.sender, "Invalid round");
return;
}
if (calcPlayerEarnings() < _value) {
// Not enough earnings in player vault
emit OnTransactionFail(msg.sender, "Insufficient funds");
return;
}
players_[msg.sender].totalReinvested = _value.add(players_[msg.sender].totalReinvested);
buyCarrotsInternal(_horse, _value, _referrerName);
}
/**
* @dev name horse by purchasing enough carrots to become majority holder
* @param _horse the horse being named
* @param _nameStr the desired horse name (See NameValidator for requirements)
* @param _referrerName the player for which to reward referral bonuses to
*/
function nameHorse(uint8 _horse, string _nameStr, bytes32 _referrerName)
public
payable
isHuman()
isValidHorse(_horse)
{
if ((rounds_[getCurrentRound()].eth[_horse])
.carrotsReceived(msg.value)
.add(players_[msg.sender].totalCarrots[_horse]) <
horses_[_horse].mostCarrotsOwned) {
emit OnTransactionFail(msg.sender, "Insufficient funds");
if (msg.value > 0) {
msg.sender.transfer(msg.value);
}
return;
}
if (msg.value > 0) {
buyCarrotsInternal(_horse, msg.value, _referrerName);
}
horses_[_horse].name = NameValidator.validate(_nameStr);
if (horses_[_horse].owner != msg.sender) {
horses_[_horse].owner = msg.sender;
}
emit OnHorseNamed(
msg.sender,
players_[msg.sender].name,
_horse,
horses_[_horse].name,
horses_[_horse].mostCarrotsOwned,
block.timestamp
);
}
/**
* @dev withdraw all earnings made so far. includes winnings, dividends, and referrals
*/
function withdrawEarnings()
public
isHuman()
{
managePlayer();
manageReferrer(msg.sender);
uint256 earnings = calcPlayerEarnings();
if (earnings > 0) {
players_[msg.sender].totalWithdrawn = earnings.add(players_[msg.sender].totalWithdrawn);
msg.sender.transfer(earnings);
}
emit OnEthWithdrawn(msg.sender, earnings);
}
/**
* @dev fallback function puts incoming eth into devs referrals
*/
function()
public
payable
{
players_[DEVADDR].totalReferrals = msg.value.add(players_[DEVADDR].totalReferrals);
}
// ___ ___ _ _ _ _ ___ ___ _ _ ___ _ ___ ___ ___ __
// | o \ o \ || | | / \|_ _|| __| | U || __|| | | o \ __|| o \/ _|
// | _/ / || V || o || | | _| | || _| | |_ | _/ _| | /\_ \
// |_| |_|\\_| \_/ |_n_||_| |___| |_n_||___||___||_| |___||_|\\|__/
//
/**
* @dev core helper method for purchasing carrots
* @param _horse the horse carrots are being purchased for
* @param _value amount of eth to spend on carrots
* @param _referrerName the player for which to reward referral bonuses to
*/
function buyCarrotsInternal(uint8 _horse, uint256 _value, bytes32 _referrerName)
private
{
// check if new round needs started and update horses pending data if necessary
manageRound();
// update players winnings and reset pending data if necessary
managePlayer();
address referrer = getReferrer(_referrerName);
// update referrers total referrals and reset pending referrals if necessary
manageReferrer(referrer);
if (referrer != DEVADDR) {
// also manage dev account unless referrer is dev
manageReferrer(DEVADDR);
}
uint256 carrots = (rounds_[rID_].eth[_horse]).carrotsReceived(_value);
/*******************/
/* Update Player */
/*******************/
players_[msg.sender].eth[rID_][_horse] =
_value.add(players_[msg.sender].eth[rID_][_horse]);
players_[msg.sender].carrots[rID_][_horse] =
carrots.add(players_[msg.sender].carrots[rID_][_horse]);
players_[msg.sender].totalEth[_horse] =
_value.add(players_[msg.sender].totalEth[_horse]);
players_[msg.sender].totalCarrots[_horse] =
carrots.add(players_[msg.sender].totalCarrots[_horse]);
// players don't recieve dividends before buying the carrots
players_[msg.sender].dividendPayouts += SafeConversions.SafeSigned(earningsPerCarrot_.mul(carrots));
/*******************/
/* Update Referrer */
/*******************/
players_[referrer].referrals[rID_][_horse] =
ninePercent(_value).add(players_[referrer].referrals[rID_][_horse]);
// one percent to devs
// reuse referrals since functionality is the same
players_[DEVADDR].referrals[rID_][_horse] =
_value.div(100).add(players_[DEVADDR].referrals[rID_][_horse]);
// check if players new amount of total carrots for this horse is greater than mostCarrotsOwned and update
if (players_[msg.sender].totalCarrots[_horse] > horses_[_horse].mostCarrotsOwned) {
horses_[_horse].mostCarrotsOwned = players_[msg.sender].totalCarrots[_horse];
}
/*******************/
/* Update Round */
/*******************/
rounds_[rID_].eth[_horse] = _value.add(rounds_[rID_].eth[_horse]);
rounds_[rID_].carrots[_horse] = carrots.add(rounds_[rID_].carrots[_horse]);
// if this horses carrots now exceeds current winner, update current winner
if (rounds_[rID_].winner != _horse &&
rounds_[rID_].carrots[_horse] > rounds_[rID_].carrots[rounds_[rID_].winner]) {
rounds_[rID_].winner = _horse;
}
/*******************/
/* Update Horse */
/*******************/
horses_[_horse].totalCarrots = carrots.add(horses_[_horse].totalCarrots);
horses_[_horse].totalEth = _value.add(horses_[_horse].totalEth);
emit OnCarrotsPurchased(
msg.sender,
players_[msg.sender].name,
rID_,
[
_horse,
rounds_[rID_].winner
],
horses_[_horse].name,
[
_value,
carrots,
rounds_[rID_].eth[_horse],
rounds_[rID_].carrots[_horse],
players_[msg.sender].eth[rID_][_horse],
players_[msg.sender].carrots[rID_][_horse]
],
roundEnds_,
block.timestamp
);
}
/**
* @dev check if now is past current rounds ends time. if so, compute round
* details and update all storage to start the next round
*/
function manageRound()
private
{
if (!isRoundOver()) {
return;
}
// round over, update dividends and start next round
uint256 earningsPerCarrotThisRound = fromEthToDivies(calcRoundLosingHorsesEth(rID_));
if (earningsPerCarrotThisRound > 0) {
earningsPerCarrot_ = earningsPerCarrot_.add(earningsPerCarrotThisRound);
}
rID_++;
roundEnds_ = block.timestamp + ROUNDMAX;
}
/**
* @dev check if a player has winnings from a previous round that have yet to
* be recorded. this needs to be called before any player interacts with Ether
* Derby to make sure there data is kept up to date
*/
function managePlayer()
private
{
uint256 unrecordedWinnings = calcUnrecordedWinnings();
if (unrecordedWinnings > 0) {
players_[msg.sender].totalWinnings = unrecordedWinnings.add(players_[msg.sender].totalWinnings);
}
// if managePlayer is being called while round is over, calcUnrecordedWinnings will include
// winnings from the current round. it's important that we store rID_+1 here to make sure
// users can't double withdraw winnings from current round
if (players_[msg.sender].roundLastManaged == rID_ && isRoundOver()) {
players_[msg.sender].roundLastManaged = rID_.add(1);
}
else if (players_[msg.sender].roundLastManaged < rID_) {
players_[msg.sender].roundLastManaged = rID_;
}
}
/**
* @dev check if a player has referral bonuses from a previous round that have yet
* to be recorded
*/
function manageReferrer(address _referrer)
private
{
uint256 unrecordedRefferals = calcUnrecordedRefferals(_referrer);
if (unrecordedRefferals > 0) {
players_[_referrer].totalReferrals =
unrecordedRefferals.add(players_[_referrer].totalReferrals);
}
if (players_[_referrer].roundLastReferred == rID_ && isRoundOver()) {
players_[_referrer].roundLastReferred = rID_.add(1);
}
else if (players_[_referrer].roundLastReferred < rID_) {
players_[_referrer].roundLastReferred = rID_;
}
}
/**
* @dev calculate total amount of carrots that have been purchased
*/
function calcTotalCarrots()
private
view
returns (uint256)
{
return horses_[H1].totalCarrots
.add(horses_[H2].totalCarrots)
.add(horses_[H3].totalCarrots)
.add(horses_[H4].totalCarrots);
}
/**
* @dev calculate players total amount of carrots including the unrecorded
*/
function calcPlayerTotalCarrots()
private
view
returns (uint256)
{
return players_[msg.sender].totalCarrots[H1]
.add(players_[msg.sender].totalCarrots[H2])
.add(players_[msg.sender].totalCarrots[H3])
.add(players_[msg.sender].totalCarrots[H4]);
}
/**
* @dev calculate players total amount of eth spent including unrecorded
*/
function calcPlayerTotalEth()
private
view
returns (uint256)
{
return players_[msg.sender].totalEth[H1]
.add(players_[msg.sender].totalEth[H2])
.add(players_[msg.sender].totalEth[H3])
.add(players_[msg.sender].totalEth[H4]);
}
/**
* @dev calculate players total earnings (able to be withdrawn)
*/
function calcPlayerEarnings()
private
view
returns (uint256)
{
return calcPlayerWinnings()
.add(calcPlayerDividends())
.add(calcPlayerReferrals())
.sub(players_[msg.sender].totalWithdrawn)
.sub(players_[msg.sender].totalReinvested);
}
/**
* @dev calculate players total winning including the unrecorded
*/
function calcPlayerWinnings()
private
view
returns (uint256)
{
return players_[msg.sender].totalWinnings.add(calcUnrecordedWinnings());
}
/**
* @dev calculate players total dividends including the unrecorded
*/
function calcPlayerDividends()
private
view
returns (uint256)
{
uint256 unrecordedDividends = calcUnrecordedDividends();
uint256 carrotBalance = calcPlayerTotalCarrots();
int256 totalDividends = SafeConversions.SafeSigned(carrotBalance.mul(earningsPerCarrot_).add(unrecordedDividends));
return SafeConversions.SafeUnsigned(totalDividends - players_[msg.sender].dividendPayouts).div(MULTIPLIER);
}
/**
* @dev calculate players total referral bonus including the unrecorded
*/
function calcPlayerReferrals()
private
view
returns (uint256)
{
return players_[msg.sender].totalReferrals.add(calcUnrecordedRefferals(msg.sender));
}
/**
* @dev calculate players unrecorded winnings (those not yet in Player.totalWinnings)
*/
function calcUnrecordedWinnings()
private
view
returns (uint256)
{
uint256 round = players_[msg.sender].roundLastManaged;
if ((round == 0) || (round > rID_) || (round == rID_ && !isRoundOver())) {
// all winnings have been recorded
return 0;
}
// round is <= rID_, not 0, and if equal then round is over
// (players eth spent on the winning horse during their last round) +
// ((players carrots for winning horse during their last round) *
// (80% of losing horses eth)) / total carrots purchased for winning horse
return players_[msg.sender].eth[round][rounds_[round].winner]
.add((players_[msg.sender].carrots[round][rounds_[round].winner]
.mul(eightyPercent(calcRoundLosingHorsesEth(round))))
.div(rounds_[round].carrots[rounds_[round].winner]));
}
/**
* @dev calculate players unrecorded dividends (those not yet reflected in earningsPerCarrot_)
*/
function calcUnrecordedDividends()
private
view
returns (uint256)
{
if (!isRoundOver()) {
// round is not over
return 0;
}
// round has ended but next round has not yet been started, so
// dividends from the current round are reflected in earningsPerCarrot_
return fromEthToDivies(calcRoundLosingHorsesEth(rID_)).mul(calcPlayerTotalCarrots());
}
/**
* @dev calculate players unrecorded referral bonus (those not yet in Player.referrals)
*/
function calcUnrecordedRefferals(address _player)
private
view
returns (uint256 ret)
{
uint256 round = players_[_player].roundLastReferred;
if (!((round == 0) || (round > rID_) || (round == rID_ && !isRoundOver()))) {
for (uint8 i = H1; i <= H4; i++) {
if (rounds_[round].winner != i) {
ret = ret.add(players_[_player].referrals[round][i]);
}
}
}
}
/**
* @dev calculate total eth from all horses except the winner
*/
function calcRoundLosingHorsesEth(uint256 _round)
private
view
returns (uint256 ret)
{
for (uint8 i = H1; i <= H4; i++) {
if (rounds_[_round].winner != i) {
ret = ret.add(rounds_[_round].eth[i]);
}
}
}
/**
* @dev calculate the change in earningsPerCarrot_ based on new eth coming in
* @param _value amount of ETH being sent out as dividends to all carrot holders
*/
function fromEthToDivies(uint256 _value)
private
view
returns (uint256)
{
// edge case where dividing by 0 would happen
uint256 totalCarrots = calcTotalCarrots();
if (totalCarrots == 0) {
return 0;
}
// multiply by MULTIPLIER to prevent integer division from returning 0
// when totalCarrots > losingHorsesEth
// divide by 10 because only 10% of losing horses ETH goes to dividends
return _value.mul(MULTIPLIER).div(10).div(totalCarrots);
}
/**
* @dev convert registered name to an address
* @param _referrerName name of player that referred current player
* @return address of referrer if valid, or last person to refer the current player,
* or the devs as a backup referrer
*/
function getReferrer(bytes32 _referrerName)
private
returns (address)
{
address referrer;
// referrer is not empty, unregistered, or same as buyer
if (_referrerName != "" && registeredNames_[_referrerName] != 0 && _referrerName != players_[msg.sender].name) {
referrer = registeredNames_[_referrerName];
} else if (players_[msg.sender].lastRef != 0) {
referrer = players_[msg.sender].lastRef;
} else {
// fallback to Devs if no referrer provided
referrer = DEVADDR;
}
if (players_[msg.sender].lastRef != referrer) {
// store last referred to allow partner to continue receiving
// future purchases from this player
players_[msg.sender].lastRef = referrer;
}
return referrer;
}
/**
* @dev calculate price of buying carrots
* @param _horse which horse to calculate price for
* @param _carrots how many carrots desired
* @return ETH required to purchase X many carrots (in large format)
*/
function calculateCurrentPrice(uint8 _horse, uint256 _carrots)
private
view
returns(uint256)
{
uint256 currTotal = 0;
if (!isRoundOver()) {
// Round is ongoing
currTotal = rounds_[rID_].carrots[_horse];
}
return currTotal.add(_carrots).ethReceived(_carrots);
}
/**
* @dev check if a round number is valid to make a purchase for
* @param _round round to check
* @return true if _round is current (or next if current is over)
*/
function isInvalidRound(uint256 _round)
private
view
returns(bool)
{
// passing _round as 0 means buy for current round
return _round != 0 && _round != getCurrentRound();
}
/**
* @dev get current round
*/
function getCurrentRound()
private
view
returns(uint256)
{
if (isRoundOver()) {
return (rID_ + 1);
}
return rID_;
}
/**
* @dev check if current round has ended based on current block timestamp
* @return true if round is over, false otherwise
*/
function isRoundOver()
private
view
returns (bool)
{
return block.timestamp >= roundEnds_;
}
/**
* @dev compute eighty percent as whats left after subtracting 10%, 1% and 9%
* @param num_ number to compute 80% of
*/
function eightyPercent(uint256 num_)
private
pure
returns (uint256)
{
// 100% - 9% - 1% - 10% = 80%
return num_.sub(ninePercent(num_)).sub(num_.div(100)).sub(num_.div(10));
}
/**
* @dev compute eighty percent as whats left after subtracting 10% twice
* @param num_ number to compute 80% of
*/
function ninePercent(uint256 num_)
private
pure
returns (uint256)
{
return num_.mul(9).div(100);
}
// _____ _____ ___ ___ _ _ _ _ _ _ _ _ _ ___ ___ _ _ _ __ __
// | __\ V /_ _|| __|| o \ \| | / \ | | | | || | | \_/ || __||_ _|| U |/ \| \/ _|
// | _| ) ( | | | _| | / \\ || o || |_ | U || | | \_/ || _| | | | ( o ) o )_ \
// |___/_n_\|_| |___||_|\\_|\_||_n_||___| |___||_| |_| |_||___| |_| |_n_|\_/|__/|__/
//
/**
* @dev get stats from current round (or the last round if new has not yet started)
* @return round id
* @return round end time
* @return horse in the lead
* @return eth for each horse
* @return carrots for each horse
* @return eth invested for each horse
* @return carrots invested for each horse
* @return horse names
*/
function getRoundStats()
public
view
returns(uint256, uint256, uint8, uint256[4], uint256[4], uint256[4], uint256[4], bytes32[4])
{
return
(
rID_,
roundEnds_,
rounds_[rID_].winner,
[
rounds_[rID_].eth[H1],
rounds_[rID_].eth[H2],
rounds_[rID_].eth[H3],
rounds_[rID_].eth[H4]
],
[
rounds_[rID_].carrots[H1],
rounds_[rID_].carrots[H2],
rounds_[rID_].carrots[H3],
rounds_[rID_].carrots[H4]
],
[
players_[msg.sender].eth[rID_][H1],
players_[msg.sender].eth[rID_][H2],
players_[msg.sender].eth[rID_][H3],
players_[msg.sender].eth[rID_][H4]
],
[
players_[msg.sender].carrots[rID_][H1],
players_[msg.sender].carrots[rID_][H2],
players_[msg.sender].carrots[rID_][H3],
players_[msg.sender].carrots[rID_][H4]
],
[
horses_[H1].name,
horses_[H2].name,
horses_[H3].name,
horses_[H4].name
]
);
}
/**
* @dev get minimal details about a specific round (returns all 0s if round not over)
* @param _round which round to query
* @return horse that won
* @return eth for each horse
* @return carrots for each horse
* @return eth invested for each horse
* @return carrots invested for each horse
*/
function getPastRoundStats(uint256 _round)
public
view
returns(uint8, uint256[4], uint256[4], uint256[4], uint256[4])
{
if ((_round == 0) || (_round > rID_) || (_round == rID_ && !isRoundOver())) {
return;
}
return
(
rounds_[rID_].winner,
[
rounds_[_round].eth[H1],
rounds_[_round].eth[H2],
rounds_[_round].eth[H3],
rounds_[_round].eth[H4]
],
[
rounds_[_round].carrots[H1],
rounds_[_round].carrots[H2],
rounds_[_round].carrots[H3],
rounds_[_round].carrots[H4]
],
[
players_[msg.sender].eth[_round][H1],
players_[msg.sender].eth[_round][H2],
players_[msg.sender].eth[_round][H3],
players_[msg.sender].eth[_round][H4]
],
[
players_[msg.sender].carrots[_round][H1],
players_[msg.sender].carrots[_round][H2],
players_[msg.sender].carrots[_round][H3],
players_[msg.sender].carrots[_round][H4]
]
);
}
/**
* @dev get stats for player
* @return total winnings
* @return total dividends
* @return total referral bonus
* @return total reinvested
* @return total withdrawn
*/
function getPlayerStats()
public
view
returns(uint256, uint256, uint256, uint256, uint256)
{
return
(
calcPlayerWinnings(),
calcPlayerDividends(),
calcPlayerReferrals(),
players_[msg.sender].totalReinvested,
players_[msg.sender].totalWithdrawn
);
}
/**
* @dev get name of player
* @return players registered name if there is one
*/
function getPlayerName()
public
view
returns(bytes32)
{
return players_[msg.sender].name;
}
/**
* @dev check if name is available
* @param _name name to check
* @return bool whether or not it is available
*/
function isNameAvailable(bytes32 _name)
public
view
returns(bool)
{
return registeredNames_[_name] == 0;
}
/**
* @dev get overall stats for EtherDerby
* @return total eth for each horse
* @return total carrots for each horse
* @return player total eth for each horse
* @return player total carrots for each horse
* @return horse names
*/
function getStats()
public
view
returns(uint256[4], uint256[4], uint256[4], uint256[4], bytes32[4])
{
return
(
[
horses_[H1].totalEth,
horses_[H2].totalEth,
horses_[H3].totalEth,
horses_[H4].totalEth
],
[
horses_[H1].totalCarrots,
horses_[H2].totalCarrots,
horses_[H3].totalCarrots,
horses_[H4].totalCarrots
],
[
players_[msg.sender].totalEth[H1],
players_[msg.sender].totalEth[H2],
players_[msg.sender].totalEth[H3],
players_[msg.sender].totalEth[H4]
],
[
players_[msg.sender].totalCarrots[H1],
players_[msg.sender].totalCarrots[H2],
players_[msg.sender].totalCarrots[H3],
players_[msg.sender].totalCarrots[H4]
],
[
horses_[H1].name,
horses_[H2].name,
horses_[H3].name,
horses_[H4].name
]
);
}
/**
* @dev returns data for past 50 rounds
* @param roundStart which round to start returning data at (0 means current)
* @return round number this index in the arrays corresponds to
* @return winning horses for past 50 finished rounds
* @return horse1 carrot amounts for past 50 rounds
* @return horse2 carrot amounts for past 50 rounds
* @return horse3 carrot amounts for past 50 rounds
* @return horse4 carrot amounts for past 50 rounds
* @return horse1 players carrots for past 50 rounds
* @return horse2 players carrots for past 50 rounds
* @return horse3 players carrots for past 50 rounds
* @return horse4 players carrots for past 50 rounds
* @return horseEth total eth amounts for past 50 rounds
* @return playerEth total player eth amounts for past 50 rounds
*/
function getPastRounds(uint256 roundStart)
public
view
returns(
uint256[50] roundNums,
uint8[50] winners,
uint256[50] horse1Carrots,
uint256[50] horse2Carrots,
uint256[50] horse3Carrots,
uint256[50] horse4Carrots,
uint256[50] horse1PlayerCarrots,
uint256[50] horse2PlayerCarrots,
uint256[50] horse3PlayerCarrots,
uint256[50] horse4PlayerCarrots,
uint256[50] horseEth,
uint256[50] playerEth
)
{
uint256 index = 0;
uint256 round = rID_;
if (roundStart != 0 && roundStart <= rID_) {
round = roundStart;
}
while (index < 50 && round > 0) {
if (round == rID_ && !isRoundOver()) {
round--;
continue;
}
roundNums[index] = round;
winners[index] = rounds_[round].winner;
horse1Carrots[index] = rounds_[round].carrots[H1];
horse2Carrots[index] = rounds_[round].carrots[H2];
horse3Carrots[index] = rounds_[round].carrots[H3];
horse4Carrots[index] = rounds_[round].carrots[H4];
horse1PlayerCarrots[index] = players_[msg.sender].carrots[round][H1];
horse2PlayerCarrots[index] = players_[msg.sender].carrots[round][H2];
horse3PlayerCarrots[index] = players_[msg.sender].carrots[round][H3];
horse4PlayerCarrots[index] = players_[msg.sender].carrots[round][H4];
horseEth[index] = rounds_[round].eth[H1]
.add(rounds_[round].eth[H2])
.add(rounds_[round].eth[H3])
.add(rounds_[round].eth[H4]);
playerEth[index] = players_[msg.sender].eth[round][H1]
.add(players_[msg.sender].eth[round][H2])
.add(players_[msg.sender].eth[round][H3])
.add(players_[msg.sender].eth[round][H4]);
index++;
round--;
}
}
/**
* @dev calculate price of buying carrots for a specific horse
* @param _horse which horse to calculate price for
* @param _carrots how many carrots desired
* @return ETH required to purchase X many carrots
*/
function getPriceOfXCarrots(uint8 _horse, uint256 _carrots)
public
view
isValidHorse(_horse)
returns(uint256)
{
return calculateCurrentPrice(_horse, _carrots.mul(1000000000000000000));
}
/**
* @dev calculate price to become majority carrot holder for a specific horse
* @param _horse which horse to calculate price for
* @return carrotsRequired
* @return ethRequired
* @return currentMax
* @return owner
* @return ownerName
*/
function getPriceToName(uint8 _horse)
public
view
isValidHorse(_horse)
returns(
uint256 carrotsRequired,
uint256 ethRequired,
uint256 currentMax,
address owner,
bytes32 ownerName
)
{
if (players_[msg.sender].totalCarrots[_horse] < horses_[_horse].mostCarrotsOwned) {
// player is not already majority holder
// Have user buy one carrot more than current max
carrotsRequired = horses_[_horse].mostCarrotsOwned.sub(players_[msg.sender].totalCarrots[_horse]).add(10**DECIMALS);
ethRequired = calculateCurrentPrice(_horse, carrotsRequired);
}
currentMax = horses_[_horse].mostCarrotsOwned;
owner = horses_[_horse].owner;
ownerName = players_[horses_[_horse].owner].name;
}
}
// __ _ ___ ___ _ ___ __ _ _ __ _ _ _ _ ___ _ ___
// / _| / \ | o \ o \/ \_ _| / _| / \ | | / _|| | || | / \|_ _/ \| o \
// ( (_ | o || / ( o ) | ( (_ | o || |( (_ | U || |_ | o || ( o ) /
// \__||_n_||_|\\_|\\\_/|_| \__||_n_||___\__||___||___||_n_||_|\_/|_|\\
//
library CalcCarrots {
using SafeMath for *;
/**
* @dev calculates number of carrots recieved given X eth
*/
function carrotsReceived(uint256 _currEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return carrots((_currEth).add(_newEth)).sub(carrots(_currEth));
}
/**
* @dev calculates amount of eth received if you sold X carrots
*/
function ethReceived(uint256 _currCarrots, uint256 _sellCarrots)
internal
pure
returns (uint256)
{
return eth(_currCarrots).sub(eth(_currCarrots.sub(_sellCarrots)));
}
/**
* @dev calculates how many carrots for a single horse given an amount
* of eth spent on that horse
*/
function carrots(uint256 _eth)
internal
pure
returns (uint256)
{
return ((((_eth).mul(62831853072000000000000000000000000000000000000)
.add(9996858654086510028837239824000000000000000000000000000000000000)).sqrt())
.sub(99984292036732000000000000000000)) / (31415926536);
}
/**
* @dev calculates how much eth would be in the contract for a single
* horse given an amount of carrots bought for that horse
*/
function eth(uint256 _carrots)
internal
pure
returns (uint256)
{
return ((15707963268).mul(_carrots.mul(_carrots)).add(((199968584073464)
.mul(_carrots.mul(1000000000000000000))) / (2))) / (1000000000000000000000000000000000000);
}
}
// __ _ ___ ___ _ _ _ ___ _ _
// / _|/ \ | __|| __| | \_/ | / \|_ _|| U |
// \_ \ o || _| | _| | \_/ || o || | | |
// |__/_n_||_| |___| |_| |_||_n_||_| |_n_|
//
/**
* @title SafeMath library from OpenZeppelin
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
}
library SafeConversions {
function SafeSigned(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
// If a is too large, the signed version will be negative.
assert(b >= 0);
return b;
}
function SafeUnsigned(int256 a) internal pure returns (uint256) {
// Only negative numbers are unsafe to make unsigned.
assert(a >= 0);
return uint256(a);
}
}
library NameValidator {
/**
* @dev throws on invalid name
* -converts uppercase to lower case
* -cannot contain space
* -cannot be only numbers
* -cannot be an address (start with 0x)
* -restricts characters to A-Z, a-z, 0-9
* @return validated string in bytes32 format
*/
function validate(string _input)
internal
pure
returns(bytes32)
{
bytes memory temp = bytes(_input);
uint256 length = temp.length;
// limited to 15 characters
require (length <= 15 && length > 0, "name must be between 1 and 15 characters");
// cannot be an address
if (temp[0] == 0x30) {
require(temp[1] != 0x78, "name cannot start with 0x");
require(temp[1] != 0x58, "name cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < length; i++) {
// if its uppercase A-Z
if (temp[i] > 0x40 && temp[i] < 0x5b) {
// convert to lower case
temp[i] = byte(uint(temp[i]) + 32);
// character is non number
if (_hasNonNumber == false) {
_hasNonNumber = true;
}
} else {
// character should be only lowercase a-z or 0-9
require ((temp[i] > 0x60 && temp[i] < 0x7b) || (temp[i] > 0x2f && temp[i] < 0x3a), "name contains invalid characters");
// check if character is non number
if (_hasNonNumber == false && (temp[i] < 0x30 || temp[i] > 0x39)) {
_hasNonNumber = true;
}
}
}
require(_hasNonNumber == true, "name cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(temp, 32))
}
return (_ret);
}
}
|
name horse by purchasing enough carrots to become majority holder _horse the horse being named _nameStr the desired horse name (See NameValidator for requirements) _referrerName the player for which to reward referral bonuses to/
|
function nameHorse(uint8 _horse, string _nameStr, bytes32 _referrerName)
public
payable
isHuman()
isValidHorse(_horse)
{
if ((rounds_[getCurrentRound()].eth[_horse])
.carrotsReceived(msg.value)
.add(players_[msg.sender].totalCarrots[_horse]) <
horses_[_horse].mostCarrotsOwned) {
emit OnTransactionFail(msg.sender, "Insufficient funds");
if (msg.value > 0) {
msg.sender.transfer(msg.value);
}
return;
}
if (msg.value > 0) {
buyCarrotsInternal(_horse, msg.value, _referrerName);
}
horses_[_horse].name = NameValidator.validate(_nameStr);
if (horses_[_horse].owner != msg.sender) {
horses_[_horse].owner = msg.sender;
}
emit OnHorseNamed(
msg.sender,
players_[msg.sender].name,
_horse,
horses_[_horse].name,
horses_[_horse].mostCarrotsOwned,
block.timestamp
);
}
| 2,484,530 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Ownable.sol";
import "./erc1820/ERC1820Client.sol";
import "./erc1820/ERC1820Implementer.sol";
import "./extensions/IAmpTokensSender.sol";
import "./extensions/IAmpTokensRecipient.sol";
import "./partitions/IAmpPartitionStrategyValidator.sol";
import "./partitions/lib/PartitionUtils.sol";
import "./codes/ErrorCodes.sol";
interface ISwapToken {
function allowance(address owner, address spender)
external
view
returns (uint256 remaining);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
/**
* @title Amp
* @notice Amp is an ERC20 compatible collateral token designed to support
* multiple classes of collateralization systems.
* @dev The Amp token contract includes the following features:
*
* Partitions
* Tokens can be segmented within a given address by "partition", which in
* practice is a 32 byte identifier. These partitions can have unique
* permissions globally, through the using of partition strategies, and
* locally, on a per address basis. The ability to create the sub-segments
* of tokens and assign special behavior gives collateral managers
* flexibility in how they are implemented.
*
* Operators
* Inspired by ERC777, Amp allows token holders to assign "operators" on
* all (or any number of partitions) of their tokens. Operators are allowed
* to execute transfers on behalf of token owners without the need to use the
* ERC20 "allowance" semantics.
*
* Transfers with Data
* Inspired by ERC777, Amp transfers can include arbitrary data, as well as
* operator data. This data can be used to change the partition of tokens,
* be used by collateral manager hooks to validate a transfer, be propagated
* via event to an off chain system, etc.
*
* Token Transfer Hooks on Send and Receive
* Inspired by ERC777, Amp uses the ERC1820 Registry to allow collateral
* manager implementations to register hooks to be called upon sending to
* or transferring from the collateral manager's address or, using partition
* strategies, owned partition space. The hook implementations can be used
* to validate transfer properties, gate transfers, emit custom events,
* update local state, etc.
*
* Collateral Management Partition Strategies
* Amp is able to define certain sets of partitions, identified by a 4 byte
* prefix, that will allow special, custom logic to be executed when transfers
* are made to or from those partitions. This opens up the possibility of
* entire classes of collateral management systems that would not be possible
* without it.
*
* These features give collateral manager implementers flexibility while
* providing a consistent, "collateral-in-place", interface for interacting
* with collateral systems directly through the Amp contract.
*/
contract Amp is IERC20, ERC1820Client, ERC1820Implementer, ErrorCodes, Ownable {
using SafeMath for uint256;
/**************************************************************************/
/********************** ERC1820 Interface Constants ***********************/
/**
* @dev AmpToken interface label.
*/
string internal constant AMP_INTERFACE_NAME = "AmpToken";
/**
* @dev ERC20Token interface label.
*/
string internal constant ERC20_INTERFACE_NAME = "ERC20Token";
/**
* @dev AmpTokensSender interface label.
*/
string internal constant AMP_TOKENS_SENDER = "AmpTokensSender";
/**
* @dev AmpTokensRecipient interface label.
*/
string internal constant AMP_TOKENS_RECIPIENT = "AmpTokensRecipient";
/**
* @dev AmpTokensChecker interface label.
*/
string internal constant AMP_TOKENS_CHECKER = "AmpTokensChecker";
/**************************************************************************/
/*************************** Token properties *****************************/
/**
* @dev Token name (Amp).
*/
string internal _name;
/**
* @dev Token symbol (Amp).
*/
string internal _symbol;
/**
* @dev Total minted supply of token. This will increase comensurately with
* successful swaps of the swap token.
*/
uint256 internal _totalSupply;
/**
* @dev The granularity of the token. Hard coded to 1.
*/
uint256 internal constant _granularity = 1;
/**************************************************************************/
/***************************** Token mappings *****************************/
/**
* @dev Mapping from tokenHolder to balance. This reflects the balance
* across all partitions of an address.
*/
mapping(address => uint256) internal _balances;
/**************************************************************************/
/************************** Partition mappings ****************************/
/**
* @dev List of active partitions. This list reflects all partitions that
* have tokens assigned to them.
*/
bytes32[] internal _totalPartitions;
/**
* @dev Mapping from partition to their index.
*/
mapping(bytes32 => uint256) internal _indexOfTotalPartitions;
/**
* @dev Mapping from partition to global balance of corresponding partition.
*/
mapping(bytes32 => uint256) public totalSupplyByPartition;
/**
* @dev Mapping from tokenHolder to their partitions.
*/
mapping(address => bytes32[]) internal _partitionsOf;
/**
* @dev Mapping from (tokenHolder, partition) to their index.
*/
mapping(address => mapping(bytes32 => uint256)) internal _indexOfPartitionsOf;
/**
* @dev Mapping from (tokenHolder, partition) to balance of corresponding
* partition.
*/
mapping(address => mapping(bytes32 => uint256)) internal _balanceOfByPartition;
/**
* @notice Default partition of the token.
* @dev All ERC20 operations operate solely on this partition.
*/
bytes32
public constant defaultPartition = 0x0000000000000000000000000000000000000000000000000000000000000000;
/**
* @dev Zero partition prefix. Partitions with this prefix can not have
* a strategy assigned, and partitions with a different prefix must have one.
*/
bytes4 internal constant ZERO_PREFIX = 0x00000000;
/**************************************************************************/
/***************************** Operator mappings **************************/
/**
* @dev Mapping from (tokenHolder, operator) to authorized status. This is
* specific to the token holder.
*/
mapping(address => mapping(address => bool)) internal _authorizedOperator;
/**************************************************************************/
/********************** Partition operator mappings ***********************/
/**
* @dev Mapping from (partition, tokenHolder, spender) to allowed value.
* This is specific to the token holder.
*/
mapping(bytes32 => mapping(address => mapping(address => uint256)))
internal _allowedByPartition;
/**
* @dev Mapping from (tokenHolder, partition, operator) to 'approved for
* partition' status. This is specific to the token holder.
*/
mapping(address => mapping(bytes32 => mapping(address => bool)))
internal _authorizedOperatorByPartition;
/**************************************************************************/
/********************** Collateral Manager mappings ***********************/
/**
* @notice Collection of registered collateral managers.
*/
address[] public collateralManagers;
/**
* @dev Mapping of collateral manager addresses to registration status.
*/
mapping(address => bool) internal _isCollateralManager;
/**************************************************************************/
/********************* Partition Strategy mappings ************************/
/**
* @notice Collection of reserved partition strategies.
*/
bytes4[] public partitionStrategies;
/**
* @dev Mapping of partition strategy flag to registration status.
*/
mapping(bytes4 => bool) internal _isPartitionStrategy;
/**************************************************************************/
/***************************** Swap storage *******************************/
/**
* @notice Swap token address. Immutable.
*/
ISwapToken public swapToken;
/**
* @notice Swap token graveyard address.
* @dev This is the address that the incoming swapped tokens will be
* forwarded to upon successfully minting Amp.
*/
address
public constant swapTokenGraveyard = 0x000000000000000000000000000000000000dEaD;
/**************************************************************************/
/** EVENTS ****************************************************************/
/**************************************************************************/
/**************************************************************************/
/**************************** Transfer Events *****************************/
/**
* @notice Emitted when a transfer has been successfully completed.
* @param fromPartition The partition from which tokens were transferred.
* @param operator The address that initiated the transfer.
* @param from The address from which the tokens were transferred.
* @param to The address to which the tokens were transferred.
* @param value The amount of tokens transferred.
* @param data Additional metadata included with the transfer. Can include
* the partition to which the tokens were transferred, if different than
* `fromPartition`.
* @param operatorData Additional metadata included with the transfer. Typically used by
* partition strategies and collateral managers to authorize transfers.
*/
event TransferByPartition(
bytes32 indexed fromPartition,
address operator,
address indexed from,
address indexed to,
uint256 value,
bytes data,
bytes operatorData
);
/**
* @notice Emitted when a transfer has been successfully completed and the
* tokens that were transferred have changed partitions.
* @param fromPartition The partition from which the tokens were transferred.
* @param toPartition The partition to which the tokens were transferred.
* @param value The amount of tokens transferred.
*/
event ChangedPartition(
bytes32 indexed fromPartition,
bytes32 indexed toPartition,
uint256 value
);
/**************************************************************************/
/**************************** Operator Events *****************************/
/**
* @notice Emitted when a token holder authorizes an address to transfer tokens on its behalf
* from a particular partition.
* @param partition The partition of the tokens from which the holder has authorized the
* `spender` to transfer.
* @param owner The token holder.
* @param spender The operator for which the `owner` has authorized the allowance.
* @param value The amount of tokens authorized for transfer.
*/
event ApprovalByPartition(
bytes32 indexed partition,
address indexed owner,
address indexed spender,
uint256 value
);
/**
* @notice Emitted when a token holder has authorized an operator to transfer tokens on the
* behalf of the holder across all partitions.
* @param operator The address that was authorized to transfer tokens on
* behalf of the `tokenHolder`.
* @param tokenHolder The address that authorized the `operator` to transfer
* their tokens.
*/
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
/**
* @notice Emitted when a token holder has deauthorized an operator from
* transferring tokens on behalf of the holder.
* @dev Note that this applies an account-wide authorization change, and does not reflect any
* change in the authorization for a particular partition.
* @param operator The address that was deauthorized from transferring tokens
* on behalf of the `tokenHolder`.
* @param tokenHolder The address that revoked the `operator`'s authorization
* to transfer their tokens.
*/
event RevokedOperator(address indexed operator, address indexed tokenHolder);
/**
* @notice Emitted when a token holder has authorized an operator to transfer
* tokens on behalf of the holder from a particular partition.
* @param partition The partition from which the `operator` is authorized to transfer.
* @param operator The address authorized to transfer tokens on
* behalf of the `tokenHolder`.
* @param tokenHolder The address that authorized the `operator` to transfer
* tokens held in partition `partition`.
*/
event AuthorizedOperatorByPartition(
bytes32 indexed partition,
address indexed operator,
address indexed tokenHolder
);
/**
* @notice Emitted when a token holder has deauthorized an operator from
* transferring held tokens from a specific partition.
* @param partition The partition for which the `operator` was deauthorized for token transfer
* on behalf of the `tokenHolder`.
* @param operator The address that was deauthorized from transferring
* tokens on behalf of the `tokenHolder`.
* @param tokenHolder The address that revoked the `operator`'s permission
* to transfer held tokens from `partition`.
*/
event RevokedOperatorByPartition(
bytes32 indexed partition,
address indexed operator,
address indexed tokenHolder
);
/**************************************************************************/
/********************** Collateral Manager Events *************************/
/**
* @notice Emitted when a collateral manager has been registered.
* @param collateralManager The address of the collateral manager.
*/
event CollateralManagerRegistered(address collateralManager);
/**************************************************************************/
/*********************** Partition Strategy Events ************************/
/**
* @notice Emitted when a new partition strategy validator is set.
* @param flag The 4 byte prefix of the partitions that the strategy affects.
* @param name The name of the interface implemented by the partition strategy.
* @param implementation The address of the partition strategy hook
* implementation.
*/
event PartitionStrategySet(bytes4 flag, string name, address indexed implementation);
// ************** Mint & Swap **************
/**
* @notice Emitted when tokens are minted, which only occurs as the result of token swap.
* @param operator Address that executed the swap, resulting in tokens being minted
* @param to Address that received the newly minted tokens.
* @param value Amount of tokens minted.
* @param data Additional metadata. Unused; required for interface compatibility.
*/
event Minted(address indexed operator, address indexed to, uint256 value, bytes data);
/**
* @notice Emitted when tokens are swapped as part of the minting process.
* @param operator Address that executed the swap.
* @param from Address whose source swap tokens were burned, and for which Amp tokens were
* minted.
* @param value Amount of tokens swapped into Amp.
*/
event Swap(address indexed operator, address indexed from, uint256 value);
/**************************************************************************/
/** CONSTRUCTOR ***********************************************************/
/**************************************************************************/
/**
* @notice Initialize Amp, initialize the default partition, and register the
* contract implementation in the global ERC1820Registry.
* @param _swapTokenAddress_ The address of the ERC-20 token that is set to be
* swappable for Amp.
* @param _name_ Name of the token to be initialized.
* @param _symbol_ Symbol of the token to be initialized.
*/
constructor(
address _swapTokenAddress_,
string memory _name_,
string memory _symbol_
) public {
// "Swap token cannot be 0 address"
require(_swapTokenAddress_ != address(0), EC_5A_INVALID_SWAP_TOKEN_ADDRESS);
swapToken = ISwapToken(_swapTokenAddress_);
_name = _name_;
_symbol = _symbol_;
_totalSupply = 0;
// Add the default partition to the total partitions on deploy
_addPartitionToTotalPartitions(defaultPartition);
// Register contract in ERC1820 registry
ERC1820Client.setInterfaceImplementation(AMP_INTERFACE_NAME, address(this));
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this));
// Indicate token verifies Amp and ERC20 interfaces
ERC1820Implementer._setInterface(AMP_INTERFACE_NAME);
ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME);
}
/**************************************************************************/
/** EXTERNAL FUNCTIONS (ERC20) ********************************************/
/**************************************************************************/
/**
* @notice Retrieves the total number of minted tokens.
* @return uint256 containing the total number of minted tokens.
*/
function totalSupply() external override view returns (uint256) {
return _totalSupply;
}
/**
* @notice Retrieves the balance of the account with address `_tokenHolder` across all partitions.
* @dev Note that this figure should not be used as the arbiter of the amount a token holder
* will successfully be able to send via the ERC-20 compatible `Amp.transfer` method. In order
* to get that figure, use `Amp.balanceOfByPartition` to get the balance of the default
* partition.
* @param _tokenHolder Address for which the balance is returned.
* @return uint256 containing the amount of tokens held by `_tokenHolder`
* across all partitions.
*/
function balanceOf(address _tokenHolder) external override view returns (uint256) {
return _balances[_tokenHolder];
}
/**
* @notice Transfers an amount of tokens to the specified address.
* @dev Note that this only transfers from the `msg.sender` address's default partition.
* To transfer from other partitions, use function `Amp.transferByPartition`.
* @param _to The address to which the tokens should be transferred.
* @param _value The amount of tokens to be transferred.
* @return bool indicating whether the operation was successful.
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
_transferByDefaultPartition(msg.sender, msg.sender, _to, _value, "");
return true;
}
/**
* @notice Transfers an amount of tokens between two accounts.
* @dev Note that this only transfers from the `_from` address's default partition.
* To transfer from other partitions, use function `Amp.transferByPartition`.
* @param _from The address from which the tokens are to be transferred.
* @param _to The address to which the tokens are to be transferred.
* @param _value The amount of tokens to be transferred.
* @return bool indicating whether the operation was successful.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) external override returns (bool) {
_transferByDefaultPartition(msg.sender, _from, _to, _value, "");
return true;
}
/**
* @notice Retrieves the allowance of tokens that has been granted by `_owner` to
* `_spender` for the default partition.
* @dev Note that this only returns the allowance of the `_owner` address's default partition.
* To retrieve the allowance for a different partition, use function `Amp.allowanceByPartition`.
* @param _owner The address holding the authorized tokens.
* @param _spender The address authorized to transfer the tokens from `_owner`.
* @return uint256 specifying the amount of tokens available for the `_spender` to transfer
* from the `_owner`'s default partition.
*/
function allowance(address _owner, address _spender)
external
override
view
returns (uint256)
{
return _allowedByPartition[defaultPartition][_owner][_spender];
}
/**
* @notice Sets an allowance for an address to transfer an amount of tokens on behalf of the
* caller.
* @dev Note that this only affects the `msg.sender` address's default partition.
* To approve transfers from other partitions, use function `Amp.approveByPartition`.
*
* This method is required for ERC-20 compatibility, but is subject to the race condition
* described in
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729.
*
* Functions `Amp.increaseAllowance` and `Amp.decreaseAllowance` should be used instead.
* @param _spender The address which is authorized to transfer tokens from default partition
* of `msg.sender`.
* @param _value The amount of tokens to be authorized.
* @return bool indicating if the operation was successful.
*/
function approve(address _spender, uint256 _value) external override returns (bool) {
_approveByPartition(defaultPartition, msg.sender, _spender, _value);
return true;
}
/**
* @notice Increases the allowance granted to `_spender` by the caller.
* @dev This is an alternative to `Amp.approve` that can be used as a mitigation for
* the race condition described in
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729.
*
* Note that this only affects the `msg.sender` address's default partition.
* To increase the allowance for other partitions, use function
* `Amp.increaseAllowanceByPartition`.
*
* #### Requirements:
* - `_spender` cannot be the zero address.
* @param _spender The account authorized to transfer the tokens.
* @param _addedValue Additional amount of the `msg.sender`'s tokens `_spender`
* is allowed to transfer.
* @return bool indicating if the operation was successful.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
external
returns (bool)
{
_approveByPartition(
defaultPartition,
msg.sender,
_spender,
_allowedByPartition[defaultPartition][msg.sender][_spender].add(_addedValue)
);
return true;
}
/**
* @notice Decreases the allowance granted to `_spender` by the caller.
* @dev This is an alternative to `Amp.approve` that can be used as a mitigation for
* the race condition described in
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729.
*
* Note that this only affects the `msg.sender` address's default partition.
* To decrease the allowance for other partitions, use function
* `decreaseAllowanceByPartition`.
*
* #### Requirements:
* - `_spender` cannot be the zero address.
* - `_spender` must have an allowance for the caller of at least `_subtractedValue`.
* @param _spender Account whose authorization to transfer tokens is to be decreased.
* @param _subtractedValue Amount by which the authorization for `_spender` to transfer tokens
* held by `msg.sender`'s account is to be decreased.
* @return bool indicating if the operation was successful.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
external
returns (bool)
{
_approveByPartition(
defaultPartition,
msg.sender,
_spender,
_allowedByPartition[defaultPartition][msg.sender][_spender].sub(
_subtractedValue
)
);
return true;
}
/**************************************************************************/
/** EXTERNAL FUNCTIONS (AMP) **********************************************/
/**************************************************************************/
/******************************** Swap ***********************************/
/**
* @notice Exchanges an amount of source swap tokens from the contract defined at deployment
* for the equivalent amount of Amp tokens.
* @dev Requires the `_from` account to have granted the Amp contract an allowance of swap
* tokens no greater than their balance.
* @param _from Token holder whose swap tokens will be exchanged for Amp tokens.
*/
function swap(address _from) public {
uint256 amount = swapToken.allowance(_from, address(this));
require(amount > 0, EC_53_INSUFFICIENT_ALLOWANCE);
require(
swapToken.transferFrom(_from, swapTokenGraveyard, amount),
EC_60_SWAP_TRANSFER_FAILURE
);
_mint(msg.sender, _from, amount);
emit Swap(msg.sender, _from, amount);
}
/**************************************************************************/
/************************** Holder information ****************************/
/**
* @notice Retrieves the balance of a token holder for a specific partition.
* @param _partition The partition for which the balance is returned.
* @param _tokenHolder Address for which the balance is returned.
* @return uint256 containing the amount of tokens held by `_tokenHolder` in `_partition`.
*/
function balanceOfByPartition(bytes32 _partition, address _tokenHolder)
external
view
returns (uint256)
{
return _balanceOfByPartition[_tokenHolder][_partition];
}
/**
* @notice Retrieves the set of partitions for a particular token holder.
* @param _tokenHolder Address for which the partitions are returned.
* @return array containing the partitions of `_tokenHolder`.
*/
function partitionsOf(address _tokenHolder) external view returns (bytes32[] memory) {
return _partitionsOf[_tokenHolder];
}
/**************************************************************************/
/************************** Advanced Transfers ****************************/
/**
* @notice Transfers tokens from a specific partition on behalf of a token
* holder, optionally changing the partition and including
* arbitrary data used by the partition strategies and collateral managers to authorize the
* transfer.
* @dev This can be used to transfer an address's own tokens, or transfer
* a different address's tokens by specifying the `_from` param. If
* attempting to transfer from a different address than `msg.sender`, the
* `msg.sender` will need to be an operator or have enough allowance for the
* `_partition` of the `_from` address.
* @param _partition The partition from which the tokens are to be transferred.
* @param _from Address from which the tokens are to be transferred.
* @param _to Address to which the tokens are to be transferred.
* @param _value Amount of tokens to be transferred.
* @param _data Information attached to the transfer. Will contain the
* destination partition if changing partitions.
* @param _operatorData Additional data attached to the transfer. Used by partition strategies
* and collateral managers to authorize the transfer.
* @return bytes32 containing the destination partition.
*/
function transferByPartition(
bytes32 _partition,
address _from,
address _to,
uint256 _value,
bytes calldata _data,
bytes calldata _operatorData
) external returns (bytes32) {
return
_transferByPartition(
_partition,
msg.sender,
_from,
_to,
_value,
_data,
_operatorData
);
}
/**************************************************************************/
/************************** Operator Management ***************************/
/**
* @notice Authorizes an address as an operator of `msg.sender` to transfer tokens on its
* behalf.
* @dev Note that this applies to all partitions.
*
* `msg.sender` is always an operator for itself, and does not need to
* be explicitly added.
* @param _operator Address to set as an operator for `msg.sender`.
*/
function authorizeOperator(address _operator) external {
require(_operator != msg.sender, EC_58_INVALID_OPERATOR);
_authorizedOperator[msg.sender][_operator] = true;
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @notice Remove the right of the `_operator` address to be an operator for
* `msg.sender` and to transfer tokens on its behalf.
* @dev Note that this affects the account-wide authorization granted via function
* `Amp.authorizeOperator`, and does not affect authorizations granted via function
* `Amp.authorizeOperatorByPartition`.
*
* `msg.sender` is always an operator for itself, and cannot be
* removed.
* @param _operator Address to be deauthorized an operator for `msg.sender`.
*/
function revokeOperator(address _operator) external {
require(_operator != msg.sender, EC_58_INVALID_OPERATOR);
_authorizedOperator[msg.sender][_operator] = false;
emit RevokedOperator(_operator, msg.sender);
}
/**
* @notice Authorizes an account as an operator of a particular partition.
* @dev The `msg.sender` is always an operator for itself, and does not need to
* be explicitly added to a partition.
* @param _partition The partition for which the `_operator` is to be authorized.
* @param _operator Address to be authorized as an operator for `msg.sender`.
*/
function authorizeOperatorByPartition(bytes32 _partition, address _operator)
external
{
require(_operator != msg.sender, EC_58_INVALID_OPERATOR);
_authorizedOperatorByPartition[msg.sender][_partition][_operator] = true;
emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender);
}
/**
* @notice Deauthorizes an address as an operator for a particular partition.
* @dev Note that this does not override an account-wide authorization granted via function
* `Amp.authorizeOperator`.
*
* `msg.sender` is always an operator for itself, and cannot be
* removed from a partition.
* @param _partition The partition for which the `_operator` is deauthorized.
* @param _operator Address to deauthorize as an operator for `msg.sender`.
*/
function revokeOperatorByPartition(bytes32 _partition, address _operator) external {
require(_operator != msg.sender, EC_58_INVALID_OPERATOR);
_authorizedOperatorByPartition[msg.sender][_partition][_operator] = false;
emit RevokedOperatorByPartition(_partition, _operator, msg.sender);
}
/**************************************************************************/
/************************** Operator Information **************************/
/**
* @notice Indicates whether the `_operator` address is an operator of the
* `_tokenHolder` address.
* @dev Note that this applies to all of the partitions of the `msg.sender` address.
* @param _operator Address which may be an operator of `_tokenHolder`.
* @param _tokenHolder Address of a token holder which may have the
* `_operator` address as an operator.
* @return bool indicating whether `_operator` is an operator of `_tokenHolder`.
*/
function isOperator(address _operator, address _tokenHolder)
external
view
returns (bool)
{
return _isOperator(_operator, _tokenHolder);
}
/**
* @notice Indicate whether the `_operator` address is an operator of the
* `_tokenHolder` address for the `_partition`.
* @param _partition Partition for which `_operator` may be authorized.
* @param _operator Address which may be an operator of `_tokenHolder` for the `_partition`.
* @param _tokenHolder Address of a token holder which may have the
* `_operator` address as an operator for the `_partition`.
* @return bool indicating whether `_operator` is an operator of `_tokenHolder` for the
* `_partition`.
*/
function isOperatorForPartition(
bytes32 _partition,
address _operator,
address _tokenHolder
) external view returns (bool) {
return _isOperatorForPartition(_partition, _operator, _tokenHolder);
}
/**
* @notice Indicates whether the `_operator` address is an operator of the
* `_collateralManager` address for the `_partition`.
* @dev This method is functionally identical to `Amp.isOperatorForPartition`, except that it
* also requires the address that `_operator` is being checked for must be
* a registered collateral manager.
* @param _partition Partition for which the operator may be authorized.
* @param _operator Address which may be an operator of `_collateralManager`
* for the `_partition`.
* @param _collateralManager Address of a collateral manager which may have
* the `_operator` address as an operator for the `_partition`.
* @return bool indicating whether the `_operator` address is an operator of the
* `_collateralManager` address for the `_partition`.
*/
function isOperatorForCollateralManager(
bytes32 _partition,
address _operator,
address _collateralManager
) external view returns (bool) {
return
_isCollateralManager[_collateralManager] &&
(_isOperator(_operator, _collateralManager) ||
_authorizedOperatorByPartition[_collateralManager][_partition][_operator]);
}
/**************************************************************************/
/***************************** Token metadata *****************************/
/**
* @notice Retrieves the name of the token.
* @return string containing the name of the token. Always "Amp".
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @notice Retrieves the symbol of the token.
* @return string containing the symbol of the token. Always "AMP".
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @notice Retrieves the number of decimals of the token.
* @return uint8 containing the number of decimals of the token. Always 18.
*/
function decimals() external pure returns (uint8) {
return uint8(18);
}
/**
* @notice Retrieves the smallest part of the token that is not divisible.
* @return uint256 containing the smallest non-divisible part of the token. Always 1.
*/
function granularity() external pure returns (uint256) {
return _granularity;
}
/**
* @notice Retrieves the set of existing partitions.
* @return array containing all partitions.
*/
function totalPartitions() external view returns (bytes32[] memory) {
return _totalPartitions;
}
/************************************************************************************************/
/******************************** Partition Token Allowances ************************************/
/**
* @notice Retrieves the allowance of tokens that has been granted by a token holder to another
* account.
* @param _partition Partition for which the spender may be authorized.
* @param _owner The address which owns the tokens.
* @param _spender The address which is authorized transfer tokens on behalf of the token
* holder.
* @return uint256 containing the amount of tokens available for `_spender` to transfer.
*/
function allowanceByPartition(
bytes32 _partition,
address _owner,
address _spender
) external view returns (uint256) {
return _allowedByPartition[_partition][_owner][_spender];
}
/**
* @notice Approves the `_spender` address to transfer the specified amount of
* tokens in `_partition` on behalf of `msg.sender`.
*
* Note that this method is subject to the race condition described in
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. Functions
* `Amp.increaseAllowanceByPartition` and `Amp.decreaseAllowanceByPartition` should be used
* instead.
* @param _partition Partition for which the `_spender` is to be authorized to transfer tokens.
* @param _spender The address of the account to be authorized to transfer tokens.
* @param _value The amount of tokens to be authorized.
* @return bool indicating if the operation was successful.
*/
function approveByPartition(
bytes32 _partition,
address _spender,
uint256 _value
) external returns (bool) {
_approveByPartition(_partition, msg.sender, _spender, _value);
return true;
}
/**
* @notice Increases the allowance granted to an account by the caller for a partition.
* @dev This is an alternative to function `Amp.approveByPartition` that can be used as
* a mitigation for the race condition described in
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* #### Requirements:
* - `_spender` cannot be the zero address.
* @param _partition Partition for which the `_spender` is to be authorized to transfer tokens.
* @param _spender The address of the account to be authorized to transfer tokens.
* @param _addedValue Additional amount of the `msg.sender`'s tokens `_spender`
* is allowed to transfer.
* @return bool indicating if the operation was successful.
*/
function increaseAllowanceByPartition(
bytes32 _partition,
address _spender,
uint256 _addedValue
) external returns (bool) {
_approveByPartition(
_partition,
msg.sender,
_spender,
_allowedByPartition[_partition][msg.sender][_spender].add(_addedValue)
);
return true;
}
/**
* @notice Decreases the allowance granted to `_spender` by the
* caller.
* @dev This is an alternative to function `Amp.approveByPartition` that can be used as
* a mitigation for the race condition described in
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* #### Requirements:
* - `_spender` cannot be the zero address.
* - `_spender` must have allowance for the caller of at least
* `_subtractedValue`.
* @param _partition Partition for which `_spender`'s allowance is to be decreased.
* @param _spender Amount by which the authorization for `_spender` to transfer tokens
* held by `msg.sender`'s account is to be decreased.
* @param _subtractedValue Amount of the `msg.sender`'s tokens `_spender` is
* no longer allowed to transfer.
* @return bool indicating if the operation was successful.
*/
function decreaseAllowanceByPartition(
bytes32 _partition,
address _spender,
uint256 _subtractedValue
) external returns (bool) {
_approveByPartition(
_partition,
msg.sender,
_spender,
_allowedByPartition[_partition][msg.sender][_spender].sub(_subtractedValue)
);
return true;
}
/**************************************************************************/
/************************ Collateral Manager Admin ************************/
/**
* @notice Registers `msg.sender` as a collateral manager.
*/
function registerCollateralManager() external {
// Short circuit a double registry
require(!_isCollateralManager[msg.sender], EC_5C_ADDRESS_CONFLICT);
collateralManagers.push(msg.sender);
_isCollateralManager[msg.sender] = true;
emit CollateralManagerRegistered(msg.sender);
}
/**
* @notice Retrieves whether the supplied address is a collateral manager.
* @param _collateralManager The address of the collateral manager.
* @return bool indicating whether `_collateralManager` is registered as a collateral manager.
*/
function isCollateralManager(address _collateralManager)
external
view
returns (bool)
{
return _isCollateralManager[_collateralManager];
}
/**************************************************************************/
/************************ Partition Strategy Admin ************************/
/**
* @notice Sets an implementation for a partition strategy identified by `_prefix`.
* @dev Note: this function can only be called by the contract owner.
* @param _prefix The 4 byte partition prefix the strategy applies to.
* @param _implementation The address of the implementation of the strategy hooks.
*/
function setPartitionStrategy(bytes4 _prefix, address _implementation) external {
require(msg.sender == owner(), EC_56_INVALID_SENDER);
require(!_isPartitionStrategy[_prefix], EC_5E_PARTITION_PREFIX_CONFLICT);
require(_prefix != ZERO_PREFIX, EC_5F_INVALID_PARTITION_PREFIX_0);
string memory iname = PartitionUtils._getPartitionStrategyValidatorIName(_prefix);
ERC1820Client.setInterfaceImplementation(iname, _implementation);
partitionStrategies.push(_prefix);
_isPartitionStrategy[_prefix] = true;
emit PartitionStrategySet(_prefix, iname, _implementation);
}
/**
* @notice Return whether the `_prefix` has had a partition strategy registered.
* @param _prefix The partition strategy identifier.
* @return bool indicating if the strategy has been registered.
*/
function isPartitionStrategy(bytes4 _prefix) external view returns (bool) {
return _isPartitionStrategy[_prefix];
}
/**************************************************************************/
/*************************** INTERNAL FUNCTIONS ***************************/
/**************************************************************************/
/**************************************************************************/
/**************************** Token Transfers *****************************/
/**
* @dev Transfer tokens from a specific partition.
* @param _fromPartition Partition of the tokens to transfer.
* @param _operator The address performing the transfer.
* @param _from Token holder.
* @param _to Token recipient.
* @param _value Number of tokens to transfer.
* @param _data Information attached to the transfer. Contains the destination
* partition if a partition change is requested.
* @param _operatorData Information attached to the transfer, by the operator
* (if any).
* @return bytes32 containing the destination partition.
*/
function _transferByPartition(
bytes32 _fromPartition,
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data,
bytes memory _operatorData
) internal returns (bytes32) {
require(_to != address(0), EC_57_INVALID_RECEIVER);
// If the `_operator` is attempting to transfer from a different `_from`
// address, first check that they have the requisite operator or
// allowance permissions.
if (_from != _operator) {
require(
_isOperatorForPartition(_fromPartition, _operator, _from) ||
(_value <= _allowedByPartition[_fromPartition][_from][_operator]),
EC_53_INSUFFICIENT_ALLOWANCE
);
// If the sender has an allowance for the partition, that should
// be decremented
if (_allowedByPartition[_fromPartition][_from][_operator] >= _value) {
_allowedByPartition[_fromPartition][_from][msg
.sender] = _allowedByPartition[_fromPartition][_from][_operator].sub(
_value
);
} else {
_allowedByPartition[_fromPartition][_from][_operator] = 0;
}
}
_callPreTransferHooks(
_fromPartition,
_operator,
_from,
_to,
_value,
_data,
_operatorData
);
require(
_balanceOfByPartition[_from][_fromPartition] >= _value,
EC_52_INSUFFICIENT_BALANCE
);
bytes32 toPartition = PartitionUtils._getDestinationPartition(
_data,
_fromPartition
);
_removeTokenFromPartition(_from, _fromPartition, _value);
_addTokenToPartition(_to, toPartition, _value);
_callPostTransferHooks(
toPartition,
_operator,
_from,
_to,
_value,
_data,
_operatorData
);
emit Transfer(_from, _to, _value);
emit TransferByPartition(
_fromPartition,
_operator,
_from,
_to,
_value,
_data,
_operatorData
);
if (toPartition != _fromPartition) {
emit ChangedPartition(_fromPartition, toPartition, _value);
}
return toPartition;
}
/**
* @notice Transfer tokens from default partitions.
* @dev Used as a helper method for ERC-20 compatibility.
* @param _operator The address performing the transfer.
* @param _from Token holder.
* @param _to Token recipient.
* @param _value Number of tokens to transfer.
* @param _data Information attached to the transfer, and intended for the
* token holder (`_from`). Should contain the destination partition if
* changing partitions.
*/
function _transferByDefaultPartition(
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data
) internal {
_transferByPartition(defaultPartition, _operator, _from, _to, _value, _data, "");
}
/**
* @dev Remove a token from a specific partition.
* @param _from Token holder.
* @param _partition Name of the partition.
* @param _value Number of tokens to transfer.
*/
function _removeTokenFromPartition(
address _from,
bytes32 _partition,
uint256 _value
) internal {
if (_value == 0) {
return;
}
_balances[_from] = _balances[_from].sub(_value);
_balanceOfByPartition[_from][_partition] = _balanceOfByPartition[_from][_partition]
.sub(_value);
totalSupplyByPartition[_partition] = totalSupplyByPartition[_partition].sub(
_value
);
// If the total supply is zero, finds and deletes the partition.
// Do not delete the _defaultPartition from totalPartitions.
if (totalSupplyByPartition[_partition] == 0 && _partition != defaultPartition) {
_removePartitionFromTotalPartitions(_partition);
}
// If the balance of the TokenHolder's partition is zero, finds and
// deletes the partition.
if (_balanceOfByPartition[_from][_partition] == 0) {
uint256 index = _indexOfPartitionsOf[_from][_partition];
if (index == 0) {
return;
}
// move the last item into the index being vacated
bytes32 lastValue = _partitionsOf[_from][_partitionsOf[_from].length - 1];
_partitionsOf[_from][index - 1] = lastValue; // adjust for 1-based indexing
_indexOfPartitionsOf[_from][lastValue] = index;
_partitionsOf[_from].pop();
_indexOfPartitionsOf[_from][_partition] = 0;
}
}
/**
* @dev Add a token to a specific partition.
* @param _to Token recipient.
* @param _partition Name of the partition.
* @param _value Number of tokens to transfer.
*/
function _addTokenToPartition(
address _to,
bytes32 _partition,
uint256 _value
) internal {
if (_value == 0) {
return;
}
_balances[_to] = _balances[_to].add(_value);
if (_indexOfPartitionsOf[_to][_partition] == 0) {
_partitionsOf[_to].push(_partition);
_indexOfPartitionsOf[_to][_partition] = _partitionsOf[_to].length;
}
_balanceOfByPartition[_to][_partition] = _balanceOfByPartition[_to][_partition]
.add(_value);
if (_indexOfTotalPartitions[_partition] == 0) {
_addPartitionToTotalPartitions(_partition);
}
totalSupplyByPartition[_partition] = totalSupplyByPartition[_partition].add(
_value
);
}
/**
* @dev Add a partition to the total partitions collection.
* @param _partition Name of the partition.
*/
function _addPartitionToTotalPartitions(bytes32 _partition) internal {
_totalPartitions.push(_partition);
_indexOfTotalPartitions[_partition] = _totalPartitions.length;
}
/**
* @dev Remove a partition to the total partitions collection.
* @param _partition Name of the partition.
*/
function _removePartitionFromTotalPartitions(bytes32 _partition) internal {
uint256 index = _indexOfTotalPartitions[_partition];
if (index == 0) {
return;
}
// move the last item into the index being vacated
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1];
_totalPartitions[index - 1] = lastValue; // adjust for 1-based indexing
_indexOfTotalPartitions[lastValue] = index;
_totalPartitions.pop();
_indexOfTotalPartitions[_partition] = 0;
}
/**************************************************************************/
/********************************* Hooks **********************************/
/**
* @notice Check for and call the `AmpTokensSender` hook on the sender address
* (`_from`), and, if `_fromPartition` is within the scope of a strategy,
* check for and call the `AmpPartitionStrategy.tokensFromPartitionToTransfer`
* hook for the strategy.
* @param _fromPartition Name of the partition to transfer tokens from.
* @param _operator Address which triggered the balance decrease (through
* transfer).
* @param _from Token holder.
* @param _to Token recipient for a transfer.
* @param _value Number of tokens the token holder balance is decreased by.
* @param _data Extra information, pertaining to the `_from` address.
* @param _operatorData Extra information, attached by the operator (if any).
*/
function _callPreTransferHooks(
bytes32 _fromPartition,
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data,
bytes memory _operatorData
) internal {
address senderImplementation;
senderImplementation = interfaceAddr(_from, AMP_TOKENS_SENDER);
if (senderImplementation != address(0)) {
IAmpTokensSender(senderImplementation).tokensToTransfer(
msg.sig,
_fromPartition,
_operator,
_from,
_to,
_value,
_data,
_operatorData
);
}
// Used to ensure that hooks implemented by a collateral manager to validate
// transfers from it's owned partitions are called
bytes4 fromPartitionPrefix = PartitionUtils._getPartitionPrefix(_fromPartition);
if (_isPartitionStrategy[fromPartitionPrefix]) {
address fromPartitionValidatorImplementation;
fromPartitionValidatorImplementation = interfaceAddr(
address(this),
PartitionUtils._getPartitionStrategyValidatorIName(fromPartitionPrefix)
);
if (fromPartitionValidatorImplementation != address(0)) {
IAmpPartitionStrategyValidator(fromPartitionValidatorImplementation)
.tokensFromPartitionToValidate(
msg.sig,
_fromPartition,
_operator,
_from,
_to,
_value,
_data,
_operatorData
);
}
}
}
/**
* @dev Check for `AmpTokensRecipient` hook on the recipient and call it.
* @param _toPartition Name of the partition the tokens were transferred to.
* @param _operator Address which triggered the balance increase (through
* transfer or mint).
* @param _from Token holder for a transfer (0x when mint).
* @param _to Token recipient.
* @param _value Number of tokens the recipient balance is increased by.
* @param _data Extra information related to the token holder (`_from`).
* @param _operatorData Extra information attached by the operator (if any).
*/
function _callPostTransferHooks(
bytes32 _toPartition,
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data,
bytes memory _operatorData
) internal {
bytes4 toPartitionPrefix = PartitionUtils._getPartitionPrefix(_toPartition);
if (_isPartitionStrategy[toPartitionPrefix]) {
address partitionManagerImplementation;
partitionManagerImplementation = interfaceAddr(
address(this),
PartitionUtils._getPartitionStrategyValidatorIName(toPartitionPrefix)
);
if (partitionManagerImplementation != address(0)) {
IAmpPartitionStrategyValidator(partitionManagerImplementation)
.tokensToPartitionToValidate(
msg.sig,
_toPartition,
_operator,
_from,
_to,
_value,
_data,
_operatorData
);
}
} else {
require(toPartitionPrefix == ZERO_PREFIX, EC_5D_PARTITION_RESERVED);
}
address recipientImplementation;
recipientImplementation = interfaceAddr(_to, AMP_TOKENS_RECIPIENT);
if (recipientImplementation != address(0)) {
IAmpTokensRecipient(recipientImplementation).tokensReceived(
msg.sig,
_toPartition,
_operator,
_from,
_to,
_value,
_data,
_operatorData
);
}
}
/**************************************************************************/
/******************************* Allowance ********************************/
/**
* @notice Approve the `_spender` address to spend the specified amount of
* tokens in `_partition` on behalf of `msg.sender`.
* @param _partition Name of the partition.
* @param _tokenHolder Owner of the tokens.
* @param _spender The address which may spend the tokens.
* @param _amount The amount of tokens available to be spent.
*/
function _approveByPartition(
bytes32 _partition,
address _tokenHolder,
address _spender,
uint256 _amount
) internal {
require(_tokenHolder != address(0), EC_56_INVALID_SENDER);
require(_spender != address(0), EC_58_INVALID_OPERATOR);
_allowedByPartition[_partition][_tokenHolder][_spender] = _amount;
emit ApprovalByPartition(_partition, _tokenHolder, _spender, _amount);
if (_partition == defaultPartition) {
emit Approval(_tokenHolder, _spender, _amount);
}
}
/**************************************************************************/
/************************** Operator Information **************************/
/**
* @dev Indicate whether the operator address is an operator of the
* tokenHolder address. An operator in this case is an operator across all
* partitions of the `msg.sender` address.
* @param _operator Address which may be an operator of `_tokenHolder`.
* @param _tokenHolder Address of a token holder which may have the `_operator`
* address as an operator.
* @return bool indicating whether `_operator` is an operator of `_tokenHolder`
*/
function _isOperator(address _operator, address _tokenHolder)
internal
view
returns (bool)
{
return (_operator == _tokenHolder ||
_authorizedOperator[_tokenHolder][_operator]);
}
/**
* @dev Indicate whether the operator address is an operator of the
* tokenHolder address for the given partition.
* @param _partition Name of the partition.
* @param _operator Address which may be an operator of tokenHolder for the
* `_partition`.
* @param _tokenHolder Address of a token holder which may have the operator
* address as an operator for the `_partition`.
* @return bool indicating whether `_operator` is an operator of `_tokenHolder` for the
* `_partition`.
*/
function _isOperatorForPartition(
bytes32 _partition,
address _operator,
address _tokenHolder
) internal view returns (bool) {
return (_isOperator(_operator, _tokenHolder) ||
_authorizedOperatorByPartition[_tokenHolder][_partition][_operator] ||
_callPartitionStrategyOperatorHook(_partition, _operator, _tokenHolder));
}
/**
* @notice Check if the `_partition` is within the scope of a strategy, and
* call it's isOperatorForPartitionScope hook if so.
* @dev This allows implicit granting of operatorByPartition permissions
* based on the partition being used being of a strategy.
* @param _partition The partition to check.
* @param _operator The address to check if is an operator for `_tokenHolder`.
* @param _tokenHolder The address to validate that `_operator` is an
* operator for.
*/
function _callPartitionStrategyOperatorHook(
bytes32 _partition,
address _operator,
address _tokenHolder
) internal view returns (bool) {
bytes4 prefix = PartitionUtils._getPartitionPrefix(_partition);
if (!_isPartitionStrategy[prefix]) {
return false;
}
address strategyValidatorImplementation;
strategyValidatorImplementation = interfaceAddr(
address(this),
PartitionUtils._getPartitionStrategyValidatorIName(prefix)
);
if (strategyValidatorImplementation != address(0)) {
return
IAmpPartitionStrategyValidator(strategyValidatorImplementation)
.isOperatorForPartitionScope(_partition, _operator, _tokenHolder);
}
// Not a partition format that imbues special operator rules
return false;
}
/**************************************************************************/
/******************************** Minting *********************************/
/**
* @notice Perform the minting of tokens.
* @dev The tokens will be minted on behalf of the `_to` address, and will be
* minted to the address's default partition.
* @param _operator Address which triggered the issuance.
* @param _to Token recipient.
* @param _value Number of tokens issued.
*/
function _mint(
address _operator,
address _to,
uint256 _value
) internal {
require(_to != address(0), EC_57_INVALID_RECEIVER);
_totalSupply = _totalSupply.add(_value);
_addTokenToPartition(_to, defaultPartition, _value);
_callPostTransferHooks(
defaultPartition,
_operator,
address(0),
_to,
_value,
"",
""
);
emit Minted(_operator, _to, _value, "");
emit Transfer(address(0), _to, _value);
emit TransferByPartition(bytes32(0), _operator, address(0), _to, _value, "", "");
}
}
|
Increases the allowance granted to an account by the caller for a partition. This is an alternative to function `Amp.approveByPartition` that can be used as a mitigation for the race condition described in Requirements: - `_spender` cannot be the zero address. _partition Partition for which the `_spender` is to be authorized to transfer tokens. _spender The address of the account to be authorized to transfer tokens. _addedValue Additional amount of the `msg.sender`'s tokens `_spender` is allowed to transfer. return bool indicating if the operation was successful./
|
function increaseAllowanceByPartition(
bytes32 _partition,
address _spender,
uint256 _addedValue
) external returns (bool) {
_approveByPartition(
_partition,
msg.sender,
_spender,
_allowedByPartition[_partition][msg.sender][_spender].add(_addedValue)
);
return true;
}
| 1,065,034 |
//Address: 0xdba0521fba14c9601812a5e58173dda953257787
//Contract name: SMINT
//Balance: 0 Ether
//Verification Date: 1/18/2018
//Transacion Count: 83
// CODE STARTS HERE
pragma solidity ^0.4.19;
contract SMINT {
struct Invoice {
address beneficiary;
uint amount;
address payer;
}
address public owner;
string public name = 'SMINT';
string public symbol = 'SMINT';
uint8 public decimals = 18;
uint public totalSupply = 100000000000000000000000000000;
uint public currentInvoice = 0;
uint public lastEfficientBlockNumber;
/* This creates an array with all balances */
mapping (address => uint) public balanceOf;
mapping (address => uint) public frozenBalanceOf;
mapping (address => uint) public successesOf;
mapping (address => uint) public failsOf;
mapping (address => mapping (address => uint)) public allowance;
mapping (uint => Invoice) public invoices;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint value);
event Mine(address indexed miner, uint value, uint rewardAddition);
event Bill(uint invoiceId);
event Pay(uint indexed invoiceId);
modifier onlyOwner {
if (msg.sender != owner) revert();
_;
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function SMINT() public {
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
lastEfficientBlockNumber = block.number;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
/* Unfreeze not more than _value tokens */
function _unfreezeMaxTokens(uint _value) internal {
uint amount = frozenBalanceOf[msg.sender] > _value ? _value : frozenBalanceOf[msg.sender];
if (amount > 0) {
balanceOf[msg.sender] += amount;
frozenBalanceOf[msg.sender] -= amount;
Transfer(this, msg.sender, amount);
}
}
function transferAndFreeze(address _to, uint _value) onlyOwner external {
require(_to != 0x0);
require(balanceOf[owner] >= _value);
require(frozenBalanceOf[_to] + _value > frozenBalanceOf[_to]);
balanceOf[owner] -= _value;
frozenBalanceOf[_to] += _value;
Transfer(owner, this, _value);
}
/* Send coins */
function transfer(address _to, uint _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function bill(uint _amount) external {
require(_amount > 0);
invoices[currentInvoice] = Invoice({
beneficiary: msg.sender,
amount: _amount,
payer: 0x0
});
Bill(currentInvoice);
currentInvoice++;
}
function pay(uint _invoiceId) external {
require(_invoiceId < currentInvoice);
require(invoices[_invoiceId].payer == 0x0);
_transfer(msg.sender, invoices[_invoiceId].beneficiary, invoices[_invoiceId].amount);
invoices[_invoiceId].payer = msg.sender;
Pay(_invoiceId);
}
/* Transfer tokens from other address */
function transferFrom(address _from, address _to, uint _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 */
function approve(address _spender, uint _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function () external payable {
if (msg.value > 0) {
revert();
}
uint minedAtBlock = uint(block.blockhash(block.number - 1));
uint minedHashRel = uint(sha256(minedAtBlock + uint(msg.sender) + block.timestamp)) % 1000000;
uint balanceRel = (balanceOf[msg.sender] + frozenBalanceOf[msg.sender]) * 1000000 / totalSupply;
if (balanceRel > 0) {
uint k = balanceRel;
if (k > 255) {
k = 255;
}
k = 2 ** k;
balanceRel = 500000 / k;
balanceRel = 500000 - balanceRel;
if (minedHashRel < balanceRel) {
uint reward = 100000000000000000 + minedHashRel * 1000000000000000;
uint rewardAddition = reward * (block.number - lastEfficientBlockNumber) * 197 / 1000000;
reward += rewardAddition;
balanceOf[msg.sender] += reward;
totalSupply += reward;
_unfreezeMaxTokens(reward);
Transfer(0, this, reward);
Transfer(this, msg.sender, reward);
Mine(msg.sender, reward, rewardAddition);
successesOf[msg.sender]++;
lastEfficientBlockNumber = block.number;
} else {
Mine(msg.sender, 0, 0);
failsOf[msg.sender]++;
}
} else {
revert();
}
}
}
|
Set allowance for other address /
|
function approve(address _spender, uint _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
| 12,871,329 |
./full_match/3/0x0d6d30018ACc4A9c6810880D913621377e9d2794/sources/contracts/NFT.sol
|
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);
}
| 8,189,997 |
./partial_match/7700/0x5A420086c66dD5241dFE5507f0d694ed86788f36/sources/test1.sol
|
Initializes the contract setting the deployer as the initial owner./
|
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
}
pragma solidity ^0.8.0;
constructor() {
_transferOwnership(_msgSender());
}
| 3,508,508 |
./full_match/5/0xe679bd4247C507AA0c1C6411b631BA4f733a50D4/sources/contracts/SmokeStake.sol
|
get unclaimedRewards of a specific user Stake in a pool uint256 unclaimedRewards = (applicableRewards getElapsedTime(_stakeId));applicableRewards are in per day so to get reward percentage for each hour divide by 24
|
function getUnclaimedRewards(uint256 _stakeId) public view returns (uint256) {
userStake memory userStakeDetails = userStakeArray[_stakeId];
uint256 stakePoolId = userStakeDetails.stakePoolId;
stakePool memory stakePoolDetails = stakePoolsById[stakePoolId];
uint256 stakeApr = getDPR(stakePoolDetails.id);
uint256 unclaimedRewards = ((applicableRewards / 24) * getElapsedTime(_stakeId));
return unclaimedRewards;
}
| 7,069,272 |
/*
freedex-protocol / User Driven Option Markets Contract used by https://www.digioptions.com
Designed to work with signatures from [www.factsigner.com](https://www.factsigner.com)
Public repository:
https://github.com/berlincode/digioptions-contracts.js
[email protected]
[email protected]
SPDX-License-Identifier: MIT
MIT License
Copyright (c) digioptions.com (https://www.digioptions.com)
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.7.0;
pragma experimental ABIEncoderV2;
import "./DigiOptionsBaseInterface.sol";
import "./DigiOptionsLib.sol";
import "./SafeCast.sol";
import "factsigner/contracts/FactsignerDefines.sol";
import "factsigner/contracts/FactsignerVerify.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
contract DigiOptionsMarkets is DigiOptionsBaseInterface {
using SafeCast for int256;
using SafeCast for uint256;
using SafeCast for int128;
using SafeCast for uint128;
using SafeMath for uint256;
using SignedSafeMath for int256;
uint256 constant private VERSION = (
(0 << 32) + /* major */
(53 << 16) + /* minor */
0 /* bugfix */
);
uint256 constant private OFFER_MAX_BLOCKS_INTO_FUTURE = 12; // increase for e.g. thundercore
// each atomic option is worth 10**9 = 1000000000 wei in case of win
uint256 constant private ATOMIC_OPTION_PAYOUT_WEI_EXP = 9;
int256 constant private ATOMIC_OPTION_PAYOUT_WEI = int256(uint256(10)**ATOMIC_OPTION_PAYOUT_WEI_EXP);
uint8 constant private RANGESTATE_NOT_USED = 0;
uint8 constant private RANGESTATE_TRADED = 1;
uint8 constant private RANGESTATE_PAYED_OUT = 2;
int256 constant private INT256_MAX = int256(~(uint256(1) << 255));
struct Position {
int128 value;
uint8 rangeState;
}
struct Market {
DigiOptionsLib.MarketState marketState;
DigiOptionsLib.MarketBaseData marketBaseData;
mapping(address => mapping(uint256 => Position)) positions; // position mapping for each user
mapping(bytes32 => uint256) offersAccepted; // remember how many options from an offer are already taken
}
struct OrderOffer {
bytes32 marketHash;
uint16 optionID;
bool buy; // does the offer owner want to buy or sell options
uint256 pricePerOption;
uint256 size;
uint256 offerID;
uint256 blockExpires;
address offerOwner;
}
struct OrderOfferSigned {
OrderOffer orderOffer;
DigiOptionsLib.Signature signature;
}
/* variables */
uint256 private timestamp;
uint256 private blockNumber;
uint256 private existingMarkets; /* one bit for each marketCategory and marketInterval */
mapping(address => uint256) internal liquidityUser;
mapping(bytes32 => Market) internal markets;
mapping(address => uint32) internal userMarketsIdx;
event MarketCreate(
bytes32 marketKey, /* marketsContract stores marketHash ; marketListerContract stores baseMarketHash */
uint48 indexed expirationDatetimeFilter,
uint40 expirationDatetime,
uint8 indexed marketInterval,
uint8 indexed marketCategory,
string underlyingString
);
event MarketSettlement(
bytes32 marketHash
);
// this may result in liquidity change
event LiquidityAddWithdraw(address indexed addr, uint256 datetime, int256 amount);
event PositionChange(
// TODO optimize order for gas costs possible?
uint256 indexed buyer,
uint256 indexed seller,
bytes32 indexed marketHash,
uint256 datetime, // TODO we might remove this and use info from block
uint16 optionID,
uint256 pricePerOption,
uint256 size,
bytes32 offerHash
);
/* This is the constructor */
constructor ()
{
blockNumber = block.number;
timestamp = block.timestamp;
}
/* TODO re-enabled after 0x-tools support solc-0.6.0
// default fallback
receive ()
external
payable
{
liquidityAdd();
}
*/
function getContractInfo (
)
external
override
virtual
returns (uint256[] memory contractInfoValues)
{
uint256[] memory infoValues = new uint[](uint256(DigiOptionsLib.InfoValues.MAX));
infoValues[uint256(DigiOptionsLib.InfoValues.CONTRACT_TYPE_IDX)] = uint256(DigiOptionsLib.ContractType.DIGIOPTIONSMARKETS);
infoValues[uint256(DigiOptionsLib.InfoValues.VERSION_MARKET_LISTER_IDX)] = 0; // versionMarketLister
infoValues[uint256(DigiOptionsLib.InfoValues.VERSION_MARKETS_IDX)] = VERSION; // versionMarkets
infoValues[uint256(DigiOptionsLib.InfoValues.DIGIOPTIONS_MARKETS_ADDR_IDX)] = uint256(uint160(address(this))); // digiOptionsMarketsAddr
infoValues[uint256(DigiOptionsLib.InfoValues.BLOCK_NUMBER_CREATED_IDX)] = blockNumber; // blockNumberCreated
infoValues[uint256(DigiOptionsLib.InfoValues.TIMESTAMP_MARKET_CREATED_IDX)] = timestamp; // timestampMarketsCreated
infoValues[uint256(DigiOptionsLib.InfoValues.OFFER_MAX_BLOCKS_INTO_FUTURE_IDX)] = OFFER_MAX_BLOCKS_INTO_FUTURE;
infoValues[uint256(DigiOptionsLib.InfoValues.ATOMIC_OPTION_PAYOUT_WEI_EXP_IDX)] = ATOMIC_OPTION_PAYOUT_WEI_EXP;
infoValues[uint256(DigiOptionsLib.InfoValues.EXISTING_MARKETS_IDX)] = existingMarkets;
return infoValues;
}
function liquidityGet()
public
view
returns (uint256 liquidity)
{
return liquidityUser[msg.sender];
}
function liquidityWithdraw (uint256 amount) external {
require (amount <= liquidityUser[msg.sender], "Not enough liquidity.");
/* Remember to reduce the liquidity BEFORE */
/* sending to prevent re-entrancy attacks */
liquidityUser[msg.sender] = liquidityUser[msg.sender].sub(amount);
payable(msg.sender).transfer(amount);
emit LiquidityAddWithdraw(msg.sender, block.timestamp, -int256(amount));
}
/* returns all relevant market data - if marketHash does not exist marketBaseData.expirationDatetime is 0*/
function getMarketDataByMarketHash (
address addr, // marketData.userState for this address
bytes32 marketHash
)
public
view
override
virtual
returns (DigiOptionsLib.MarketData memory marketData)
{
Market storage market = markets[marketHash];
DigiOptionsLib.MarketBaseData memory marketBaseData = market.marketBaseData;
DigiOptionsLib.MarketState memory marketState = market.marketState;
return DigiOptionsLib.MarketData({
marketBaseData: marketBaseData,
marketState: marketState,
marketHash: marketHash,
userState: getUserState(addr, market),
testMarket: false // only used by MarketLister
});
}
function getMarketBaseDataByMarketHash (bytes32 marketHash)
public
view
returns (DigiOptionsLib.MarketBaseData memory marketBaseData)
{
Market storage market = markets[marketHash];
return market.marketBaseData;
}
function getMarketDataListByMarketKeys (
address addr, // marketData.userState for this address
bytes32[] calldata marketKeys // marketsContract uses marketHash / marketListerContract uses baseMarketHash
)
external
view
override
virtual
returns (DigiOptionsLib.MarketData[] memory marketDataList)
{
marketDataList = new DigiOptionsLib.MarketData[](marketKeys.length);
uint256 idx;
for (idx= 0 ; idx < marketKeys.length ; idx++) {
marketDataList[idx] = getMarketDataByMarketHash(addr, marketKeys[idx]);
}
return marketDataList;
}
function calcMarketInterval (
uint40 expirationDatetime
)
external
view
override
virtual
returns (uint8 interval)
{
return DigiOptionsLib.calcMarketInterval(expirationDatetime);
}
function getUserState (
address addr,
Market storage market
)
internal
view
returns (DigiOptionsLib.UserState userState)
{
mapping(uint256 => Position) storage positions = market.positions[addr];
if (market.marketState.settled){
Position memory winningPosition = positions[market.marketState.winningOptionID];
if (
(winningPosition.rangeState == RANGESTATE_PAYED_OUT) ||
((winningPosition.rangeState == RANGESTATE_TRADED) && (winningPosition.value == 0)) // TODO fixme == 0
){
return DigiOptionsLib.UserState.PAYED_OUT;
}
}
// TODO for named markets one excess optionID is checked (which should not be a problem)
for (uint256 optionID = 0; optionID <= market.marketBaseData.strikes.length; optionID++) {
if (positions[optionID].rangeState > RANGESTATE_NOT_USED) {
return DigiOptionsLib.UserState.EXISTS;
}
}
return DigiOptionsLib.UserState.NONE;
}
function getLiquidityAndPositions (bytes32 marketHash)
external
view
returns (uint256 liquidity, Position[] memory positions, DigiOptionsLib.UserState userState)
{
Market storage market = markets[marketHash];
DigiOptionsLib.MarketBaseData memory marketBaseData = market.marketBaseData;
// return user's total contract liquidity and positions for selected market
// TODO for named markets one excess optionID is checked (which should not be a problem)
positions = new Position[](marketBaseData.strikes.length + 1);
for (uint256 optionID = 0; optionID <= marketBaseData.strikes.length; optionID++) {
positions[optionID] = market.positions[msg.sender][optionID];
}
return (
liquidityUser[msg.sender],
positions,
getUserState(msg.sender, market)
);
}
function liquidityAdd ()
public
payable
{
if (msg.value > 0) {
liquidityUser[msg.sender] = liquidityUser[msg.sender].add(msg.value);
emit LiquidityAddWithdraw(msg.sender, block.timestamp, int256(msg.value));
}
}
function liquidityAddFor (address user)
public
payable
{
if (msg.value > 0) {
liquidityUser[user] = liquidityUser[user].add(msg.value);
emit LiquidityAddWithdraw(user, block.timestamp, int256(msg.value));
}
}
function createMarket (
DigiOptionsLib.MarketBaseData memory marketBaseData,
bool testMarket,
FactsignerVerify.Signature memory signature
)
public // this should be external (see https://github.com/ethereum/solidity/issues/5479)
override
returns (bytes32 marketHash)
{
assert(marketBaseData.expirationDatetime != 0);
{ // scope here to safe stack space
bytes32 factHash = DigiOptionsLib.calcFactHash(marketBaseData);
require(
FactsignerVerify.verifyFactsignerMessage(
factHash,
signature
) == marketBaseData.signerAddr,
"Signature invalid."
);
marketHash = DigiOptionsLib.calcMarketHash(marketBaseData);
}
/* Check that the market does not already exists */
if (markets[marketHash].marketBaseData.expirationDatetime != 0)
return marketHash;
assert(marketBaseData.baseUnitExp == 18); // TODO remove this in the future
assert(marketBaseData.marketCategory < 64); // limit marketCategory (for now)
//assert((uint256(marketBaseData.transactionFee0)).add(uint256(marketBaseData.transactionFee1)).add(uint256(marketBaseData.transactionFeeSigner)) <= 500);
uint256 optionID;
if ((marketBaseData.config & uint8(FactsignerDefines.ConfigMask.ConfigMarketTypeIsStrikedMask)) != 0) {
/* striked market */
/* check that we have at least one strike */
assert(marketBaseData.strikes.length > 0);
assert(marketBaseData.strikes.length < 32765); // our first optionID is 0
/* check strikes are ordered */
for (optionID = 1; optionID < marketBaseData.strikes.length; optionID++) {
assert(marketBaseData.strikes[optionID-1] < marketBaseData.strikes[optionID]);
}
/* check that the final settlement precision high enough for the supplied strikes */
assert(int16(uint16(marketBaseData.baseUnitExp)) >= marketBaseData.ndigit);
for (optionID = 0; optionID < marketBaseData.strikes.length; optionID++) {
assert((marketBaseData.strikes[optionID] % int256(10**uint256((int256(uint256(marketBaseData.baseUnitExp))-marketBaseData.ndigit)))) == 0);
}
} else {
/* named market */
/* check that we have at least two named ranges */
assert(marketBaseData.strikes.length > 1);
assert(marketBaseData.strikes.length <= 32765); // our first optionID is 0
}
assert(marketBaseData.marketCategory < 32); // limit marketCategory (for now)
uint256 existingMarketsBit = (1 << uint256(marketBaseData.marketInterval)) << (marketBaseData.marketCategory * 8);
if (existingMarkets & existingMarketsBit == 0) {
existingMarkets = existingMarkets | existingMarketsBit;
}
uint8 marketIntervalForEventFilter = DigiOptionsLib.calcMarketInterval(marketBaseData.expirationDatetime);
if ((marketBaseData.config & uint8(FactsignerDefines.ConfigMask.ConfigIntervalTypeIsUsedMask) != 0)) {
/* interval used */
assert(marketBaseData.marketInterval == marketIntervalForEventFilter);
} else {
/* interval unused */
assert(marketBaseData.marketInterval == uint8(FactsignerDefines.MarketInterval.NONE));
}
markets[marketHash].marketBaseData = marketBaseData;
emit MarketCreate(
marketHash, // marketKey
((marketBaseData.expirationDatetime/DigiOptionsLib.getDivider(marketIntervalForEventFilter)) << 8) + marketIntervalForEventFilter,
marketBaseData.expirationDatetime,
marketBaseData.marketInterval,
marketBaseData.marketCategory,
marketBaseData.underlyingString
);
return marketHash;
}
function settlement (
bytes32 marketHash, /* market to settle */
FactsignerVerify.Signature memory signature,
int256 value,
address[] memory users,
bytes32[] memory offerHash
)
public // this should be external (see https://github.com/ethereum/solidity/issues/5479)
{
Market storage market = markets[marketHash];
/* anybody with access to the signed value (from signerAddr) can settle the market */
require(
FactsignerVerify.verifyFactsignerMessage(
keccak256(
abi.encodePacked(
DigiOptionsLib.calcFactHash(market.marketBaseData),
value,
uint16(FactsignerDefines.SettlementType.FINAL)
)
),
signature
) == market.marketBaseData.signerAddr,
"Signature invalid."
);
// just return if already settled
if (market.marketState.settled)
return;
uint256 winningOptionID;
uint256 optionID;
if ((market.marketBaseData.config & uint8(FactsignerDefines.ConfigMask.ConfigMarketTypeIsStrikedMask)) != 0) {
/* striked market */
winningOptionID = market.marketBaseData.strikes.length;
for (optionID = 0; optionID < market.marketBaseData.strikes.length; optionID++) {
if (value < market.marketBaseData.strikes[optionID]) {
winningOptionID = optionID;
break;
}
}
} else {
/* named market */
winningOptionID = 0; // default in case nothing matches
for (optionID = 0; optionID < market.marketBaseData.strikes.length; optionID++) {
if (value == market.marketBaseData.strikes[optionID]) {
winningOptionID = optionID;
break;
}
}
}
// TODO one transaction
market.marketState.winningOptionID = uint16(winningOptionID);
market.marketState.settled = true;
uint256 feeSum = uint256(market.marketBaseData.transactionFee0).add(uint256(market.marketBaseData.transactionFee1)).add(uint256(market.marketBaseData.transactionFeeSigner));
uint256 feePart = uint256(market.marketState.fee) / feeSum;
liquidityUser[market.marketBaseData.feeTaker0] = liquidityUser[market.marketBaseData.feeTaker0].add(feePart.mul(market.marketBaseData.transactionFee0));
liquidityUser[market.marketBaseData.feeTaker1] = liquidityUser[market.marketBaseData.feeTaker1].add(feePart.mul(market.marketBaseData.transactionFee1));
liquidityUser[market.marketBaseData.signerAddr] = liquidityUser[market.marketBaseData.signerAddr].add(feePart.mul(market.marketBaseData.transactionFeeSigner));
emit MarketSettlement(marketHash);
freeLiquidity(
marketHash,
users,
offerHash
);
}
function freeLiquidity(
bytes32 marketHash,
address[] memory users,
bytes32[] memory offerHash
)
public
{
Market storage market = markets[marketHash];
DigiOptionsLib.MarketState memory marketState = market.marketState;
// TODO fetch marketState once
uint16 winningOptionID = marketState.winningOptionID;
require(marketState.settled == true, "Market not yet settled.");
uint256 idx;
int256 minPosition;
for (idx = 0; idx < users.length; idx++) {
address user = users[idx];
//mapping(uint256 => Position) storage positions = market.positions[user];
if (getUserState(user, market) != DigiOptionsLib.UserState.PAYED_OUT) {
minPosition = getMinPosition(
market,
user
);
int256 pos = int256(market.positions[user][winningOptionID].value);
int256 size = pos.sub(minPosition);
market.positions[user][winningOptionID].rangeState = RANGESTATE_PAYED_OUT;
liquidityUser[user] = liquidityUser[user].add(size.mul(ATOMIC_OPTION_PAYOUT_WEI).castToUint());
// TODO a cheaper event would do too
if (pos >= 0) {
emit PositionChange(
//uint256(buyer) + uint256(market.userData[msg.sender].state),
0, // indicates final payout
uint256(uint160(user)),
marketHash,
block.timestamp,
winningOptionID,
uint256(ATOMIC_OPTION_PAYOUT_WEI),
uint256(pos),
0
);
} else {
emit PositionChange(
//uint256(buyer) + uint256(market.userData[msg.sender].state),
uint256(uint160(user)),
0, // indicates final payout
marketHash,
block.timestamp,
winningOptionID,
uint256(ATOMIC_OPTION_PAYOUT_WEI),
uint256(-pos),
0
);
}
}
}
}
function orderExecuteTest (
OrderOfferSigned memory orderOfferSigned,
uint256 sizeAccept // TODO rename to sizeAcceptMax?
)
public
view
returns (
uint256 sizeAcceptPossible,
bytes32 offerHash,
int256 liquidityOfferOwner, // only valid if sizeAcceptPossible > 0
int256 liquidityOfferTaker, // only valid if sizeAcceptPossible > 0
uint256 transactionFeeAmount // only valid if sizeAcceptPossible > 0
)
{
OrderOffer memory orderOffer = orderOfferSigned.orderOffer;
Market storage market = markets[orderOffer.marketHash];
offerHash = keccak256(
abi.encodePacked(
address(this), // this checks that the signature is valid only for this contract
orderOffer.marketHash,
orderOffer.optionID,
orderOffer.buy,
orderOffer.pricePerOption,
orderOffer.size,
orderOffer.offerID,
orderOffer.blockExpires,
orderOffer.offerOwner
)
);
if (!(
(DigiOptionsLib.verifyOffer(
offerHash,
orderOfferSigned.signature
) == orderOffer.offerOwner)
)) {
sizeAccept = 0;
// TODO return immediately?
} else if (market.offersAccepted[offerHash].add(sizeAccept) > orderOffer.size) {
sizeAccept = orderOffer.size.sub(market.offersAccepted[offerHash]);
}
uint256 value = sizeAccept.mul(orderOffer.pricePerOption);
// TODO precalcuate sum of transactions fees
transactionFeeAmount = value.div(10000).mul(
uint256(market.marketBaseData.transactionFee0).add(uint256(market.marketBaseData.transactionFee1)).add(uint256(market.marketBaseData.transactionFeeSigner))
);
liquidityOfferOwner = getLiquidityAfterTrade(
market,
orderOffer.buy,
orderOffer,
orderOffer.offerOwner,
sizeAccept,
value
);
liquidityOfferTaker = getLiquidityAfterTrade(
market,
!orderOffer.buy,
orderOffer,
msg.sender,
sizeAccept,
value
).sub(transactionFeeAmount.castToInt());
if (!(
(orderOffer.optionID <= market.marketBaseData.strikes.length) && // TODO depends on striked or named market?
(block.number <= orderOffer.blockExpires) &&
(block.number.add(OFFER_MAX_BLOCKS_INTO_FUTURE) >= orderOffer.blockExpires) &&
// offerTaker and offerOwner must not be the same (because liquidity is calculated seperately)
(orderOffer.offerOwner != msg.sender) &&
(liquidityOfferOwner >= int256(0)) &&
(liquidityOfferTaker >= int256(0))
)) {
sizeAccept = 0;
}
return (
sizeAccept,
offerHash,
liquidityOfferOwner, // only valid if sizeAcceptPossible > 0
liquidityOfferTaker, // only valid if sizeAcceptPossible > 0
transactionFeeAmount // only valid if sizeAcceptPossible > 0
);
}
function orderExecuteSingle (
OrderOfferSigned memory orderOfferSigned,
uint256 sizeAcceptMax /* maximum */
)
private
returns (uint256 sizeAcceptRemain)
{
OrderOffer memory orderOffer;
orderOffer = orderOfferSigned.orderOffer;
bytes32 offerHash;
uint256 sizeAcceptPossible;
Market storage market = markets[orderOffer.marketHash];
address buyer; // buys options / money giver
address seller; // sells options / money getter
if (orderOffer.buy) {
buyer = orderOffer.offerOwner;
seller = msg.sender;
} else {
buyer = msg.sender;
seller = orderOffer.offerOwner;
}
int256 liquidityOfferOwner; // only valid if sizeAcceptPossible > 0
int256 liquidityOfferTaker; // only valid if sizeAcceptPossible > 0
uint256 transactionFeeAmount; // only valid if sizeAcceptPossible > 0
(
sizeAcceptPossible,
offerHash,
liquidityOfferOwner, // only valid if sizeAcceptPossible > 0
liquidityOfferTaker, // only valid if sizeAcceptPossible > 0
transactionFeeAmount // only valid if sizeAcceptPossible > 0
) = orderExecuteTest (
orderOfferSigned,
sizeAcceptMax
);
if (sizeAcceptPossible == 0) {
return sizeAcceptMax;
}
liquidityUser[orderOffer.offerOwner] = liquidityOfferOwner.castToUint();
liquidityUser[msg.sender] = liquidityOfferTaker.castToUint();
market.marketState.fee = uint256(market.marketState.fee).add(transactionFeeAmount).castToUint128();
{
// update positions
Position memory pos;
{
mapping(uint256 => Position) storage positions = market.positions[buyer];
pos = positions[orderOffer.optionID];
pos.rangeState = RANGESTATE_TRADED;
pos.value = int256(pos.value).add(int256(sizeAcceptPossible)).castToInt128();
positions[orderOffer.optionID] = pos;
}
{
mapping(uint256 => Position) storage positions = market.positions[seller];
pos = positions[orderOffer.optionID];
pos.value = int256(pos.value).sub(int256(sizeAcceptPossible)).castToInt128();
pos.rangeState = RANGESTATE_TRADED;
positions[orderOffer.optionID] = pos;
}
}
// remember that (some amount of) the offers is taken
market.offersAccepted[offerHash] = market.offersAccepted[offerHash].add(sizeAcceptPossible);
emit PositionChange(
//uint256(buyer) + uint256(market.userData[msg.sender].state),
uint256(uint160(buyer)),
uint256(uint160(seller)),
orderOffer.marketHash,
block.timestamp,
orderOffer.optionID,
orderOffer.pricePerOption,
sizeAcceptPossible,
offerHash
);
return sizeAcceptMax.sub(sizeAcceptPossible);
}
// OrderOfferSigned array should contain only sell orders or only buys orders for the same optionID and marketHash (not mixed)
function orderExecute (
OrderOfferSigned[] memory orderOfferSignedList,
uint256 sizeAcceptMax /* maximum for all supplied orderOfferSigned structs */
)
public // this should be external (see https://github.com/ethereum/solidity/issues/5479)
{
OrderOfferSigned memory orderOfferSigned;
for (uint256 orderOfferIdx=0; orderOfferIdx < orderOfferSignedList.length; orderOfferIdx++) {
orderOfferSigned = orderOfferSignedList[orderOfferIdx];
//Market storage market = markets[orderOfferSigned.orderOffer.marketHash];
sizeAcceptMax = orderExecuteSingle (
orderOfferSigned,
sizeAcceptMax
);
}
}
function getLiquidityAfterTrade(
Market storage market,
bool isBuyer,
OrderOffer memory orderOffer,
address userAddr,
uint256 sizeAccept,
uint256 value
)
internal
view
returns (int256 _liquidity)
{
int256 liquidity = liquidityUser[userAddr].castToInt();
int256 sizeAccept_;
if (! isBuyer) {
liquidity = liquidity.add(value.castToInt()); // seller gets money
sizeAccept_ = int256(0).sub(sizeAccept.castToInt());
} else {
liquidity = liquidity.sub(value.castToInt()); // buyer pays money
sizeAccept_ = sizeAccept.castToInt();
}
int256 minPositionBeforeTrade;
int256 minPositionAfterTrade;
(minPositionBeforeTrade, minPositionAfterTrade) = getMinPositionAfterTrade(
market,
userAddr,
orderOffer.optionID,
sizeAccept_
);
liquidity = liquidity.add((minPositionAfterTrade.sub(minPositionBeforeTrade)).mul(ATOMIC_OPTION_PAYOUT_WEI));
return liquidity;
}
function getMinPositionAfterTrade (
Market storage market,
address userAddr,
/* optional to calc the minimal position after a change */
uint16 optionID,
int256 positionChange
) internal view
returns (int256 minPositionBeforeTrade_, int256 minPositionAfterTrade_)
{
int256 minPositionBeforeTrade = INT256_MAX;
int256 minPositionAfterTrade = INT256_MAX;
uint256 length = market.marketBaseData.strikes.length;
mapping(uint256 => Position) storage positions = market.positions[userAddr];
int256 position;
for (uint256 s = 0; s <= length; s++) {
position = positions[s].value;
if (position < minPositionBeforeTrade)
minPositionBeforeTrade = position;
if (s == optionID)
position = position.add(positionChange);
if (position < minPositionAfterTrade)
minPositionAfterTrade = position;
}
return (minPositionBeforeTrade, minPositionAfterTrade);
}
function getMinPosition (
Market storage market,
address userAddr
) internal view
returns (int256 minPosition_)
{
int256 minPosition = INT256_MAX;
uint256 length = market.marketBaseData.strikes.length;
mapping(uint256 => Position) storage positions = market.positions[userAddr];
int256 position;
for (uint256 s = 0; s <= length; s++) {
position = positions[s].value;
if (position < minPosition)
minPosition = position;
}
return (minPosition);
}
}
|
returns all relevant market data - if marketHash does not exist marketBaseData.expirationDatetime is 0/
|
function getMarketDataByMarketHash (
bytes32 marketHash
)
public
view
override
virtual
returns (DigiOptionsLib.MarketData memory marketData)
{
Market storage market = markets[marketHash];
DigiOptionsLib.MarketBaseData memory marketBaseData = market.marketBaseData;
DigiOptionsLib.MarketState memory marketState = market.marketState;
return DigiOptionsLib.MarketData({
marketBaseData: marketBaseData,
marketState: marketState,
marketHash: marketHash,
userState: getUserState(addr, market),
});
}
| 976,341 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './utils/MerkleProof.sol';
import '@openzeppelin/contracts/access/AccessControlEnumerable.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import 'erc721a/contracts/ERC721A.sol';
/**
* @title Meta DAO NFT
*
* @notice This implements the contract for the Meta DAO NFT.
* Contract can be paused by disabling public mints and creating a bogus merkle
* root tree for the whitelist. Funds from sales can be withdrawn any time by
* anyone and will withdrawn to founders + artist. All founders on the contract
* share a 90% split and can be removed. The artist gets a 10% split and
* can never be removed.
*/
contract MetaDaoNft is ERC721A, Ownable, AccessControlEnumerable {
/// @dev The price of a single mint in Ether
uint256 public constant PRICE = 0.04 ether;
/// @dev Hardcoded cap on the maximum number of mints.
uint256 public constant MAX_MINTS = 4444;
/// @dev A role for people who are project founders.
bytes32 public constant FOUNDER_ROLE = keccak256('FOUNDER_ROLE');
/// @dev A role for the artist.
bytes32 public constant ARTIST_ROLE = keccak256('ARTIST_ROLE');
/// @dev Holds the value of the baseURI for token generation
string private _baseTokenURI;
/// @dev A mapping of addresses to claimable mints
mapping(address => uint256) public staffAllocations;
/**
* @dev Indicates if public minting is opened. If true, addresses not on the
* whitelist can mint tokens. If false, the address must be on the whitelist
* to mint.
*/
bool public isPublicMintingAllowed = false;
/**
* @dev A merkle tree root for the whitelist. The merkle tree is generated
* off-chain to save gas, and the root is stored on contract for verification.
*/
bytes32 private _whitelistMerkleRoot;
/// @dev An event emitted when the mint was successful.
event SuccessfulMint(uint256 numMints, address recipient);
/// @dev An event emitted when funds have been received.
event ReceivedFunds(uint256 msgValue);
/// @dev Gates functions that should only be called by the contract admins.
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Must be an admin.');
_; // Executes the rest of the modified function
}
/// @dev Gates functions that should only be called by people who have claimable free mints
modifier onlyWithAllocation() {
uint256 claimableMints = staffAllocations[_msgSender()];
require(claimableMints > 0, 'Must have claimable mints');
_; // Executes the rest of the modified function
}
/**
* @dev Gates functions that should only be called if there are mints left
*
* @param numMints The number of mints attempting to be minted.
*/
modifier onlyWithMintsLeft(uint256 numMints) {
require(totalSupply() != MAX_MINTS, 'Soldout!');
require(totalSupply() + numMints <= MAX_MINTS, 'Not enough mints left.');
_; // Executes the rest of the modified function
}
/**
* @notice Deploys the contract, sets the baseTokenURI, sets the the max
* mints, roles for founders and disables public minting.
*
* @param founders The addresses of founders to be granted founder role.
* @param artist The address of the artist to be granted artist role.
* @param staff The address of the staff members who will be granted 5 free mints
* @param newBaseURI The base URI for the artwork generated for this contract
*/
constructor(
address[] memory founders,
address artist,
address[] memory staff,
string memory newBaseURI
) ERC721A('Meta DAO NFT', 'METADAONFT') {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_baseTokenURI = newBaseURI;
for (uint256 i = 0; i < staff.length; i++) {
address staffAddress = staff[i];
staffAllocations[staffAddress] = 5; // 5 claimable mints per staff member
}
for (uint256 i = 0; i < founders.length; i++) {
address founderAddress = founders[i];
staffAllocations[founderAddress] = 20; // 20 claimable mints per founder
}
staffAllocations[artist] = 20; // 20 claimable mints for artist
_setupRole(ARTIST_ROLE, artist);
for (uint256 i = 0; i < founders.length; i++) {
_setupRole(FOUNDER_ROLE, founders[i]);
}
}
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
/**
* @notice Admin-only function to set the whitelist with a merkle root that
* is generated off-chain.
*
* @param whitelistMerkleRoot An off-chain-generated merkle root for a list
* of addresses that should be whitelisted. For more info on generating
* merkle roots off chain for this contract, see:
* https://dev.to/0xmojo7/merkle-tree-solidity-sc-validation-568m
*/
function updateWhitelist(bytes32 whitelistMerkleRoot) public onlyAdmin {
_whitelistMerkleRoot = whitelistMerkleRoot;
}
/**
* @notice Verifies the whitelist status of a recipient address.
* @dev To generate the parameters for this function, see:
* https://dev.to/0xmojo7/merkle-tree-solidity-sc-validation-568m
* https://github.com/miguelmota/merkletreejs/
*
* @param recipient The address to check.
* @param _proof Array of hex values denoting the kekkack hashes of leaves
* in the merkle root tree leading to verified address.
* @param _positions Array of string values of 'left' or 'right' denoting the
* position of the address in the corresponding _proof array to navigate to
* the verifiable address.
*
* @return True if the address is whitelisted, false otherwise.
*/
function verifyWhitelist(
address recipient,
bytes32[] memory _proof,
uint256[] memory _positions
) public view returns (bool) {
if (_proof.length == 0 || _positions.length == 0) {
return false;
} else {
bytes32 _leaf = keccak256(abi.encodePacked(recipient));
return MerkleProof.verify(_whitelistMerkleRoot, _leaf, _proof, _positions);
}
}
/**
* @notice Mints new tokens for the recipient. Admins can mint any number of
* free tokens per transaction, for use in marketing purposes or to give away.
* During whitelist, the sender must be whitelisted and provide a proof and
* position in the Merkle Tree. During whitelist, there's a max of 2 mints
* per tx. During public sales, there's a max of 5 mints per tx. The value
* of the transaction must be at least the mint price multiplied by the
* number of mints being minted.
*
* @dev To generate the _proof and _positions parameters for this function, see:
* https://dev.to/0xmojo7/merkle-tree-solidity-sc-validation-568m
* https://github.com/miguelmota/merkletreejs/
*
* @param recipient The address to receive the newly minted tokens
* @param numMints The number of mints to mint
* @param _proof Array of hex values denoting the kekkack hashes of leaves
* in the merkle root tree leading to verified address. Used to verify the
* recipient is whitelisted, if minting during whitelist period.
* @param _positions Array of string values of 'left' or 'right' denoting the
* position of the address in the corresponding _proof array to navigate to
* the verifiable address. Used to verify the is whitelisted, if minting
* during whitelist period.
*/
function mint(
address recipient,
uint8 numMints,
bytes32[] memory _proof,
uint256[] memory _positions
) public payable onlyWithMintsLeft(numMints) {
require(numMints > 0, 'Must provide an amount to mint.');
if (!hasRole(DEFAULT_ADMIN_ROLE, _msgSender())) {
require(msg.value >= PRICE * numMints, 'Value below price');
if (isPublicMintingAllowed) {
require(numMints <= 5, 'Can mint a max of 5 during public sale');
} else {
require(verifyWhitelist(_msgSender(), _proof, _positions), 'Not on whitelist.');
require(numMints <= 2, 'Can mint a max of 2 during presale');
}
}
_safeMint(recipient, numMints);
emit SuccessfulMint(numMints, recipient);
}
/**
* @notice Mints claimable tokens for staff members, artist, and founders.
*
* @dev This function pulls the allocations from the staffAllocations map,
* and mints the appropriate number of mints for the address claiming, then
* marks the mints as claimed by setting the value in the map to 0.
*/
function staffMint() public onlyWithAllocation onlyWithMintsLeft(staffAllocations[_msgSender()]) {
_safeMint(_msgSender(), staffAllocations[_msgSender()]);
staffAllocations[_msgSender()] = 0;
emit SuccessfulMint(staffAllocations[_msgSender()], _msgSender());
}
/**
* @notice Enables public minting. When enabled, addresses that are not on
* the whitelist are able to mint.
*/
function allowPublicMinting() public onlyAdmin {
isPublicMintingAllowed = true;
}
/**
* @notice Enables public minting. When enabled, addresses that are not on
* the whitelist are able to mint.
*/
function disallowPublicMinting() public onlyAdmin {
isPublicMintingAllowed = false;
}
/**
* @dev All interfaces need to support `supportsInterface`. This function
* checks if the provided interface ID is supported.
*
* @param interfaceId The interface ID to check.
*
* @return True if the interface is supported (AccessControlEnumerable,
* ERC721, ERC721Enumerable), false otherwise.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC721A)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @notice Withdraws all funds from contract address. Founders get 90%,
* artist gets remaining 10%.
*
*/
function withdrawAll() public {
uint256 balance = address(this).balance;
uint256 founderCount = getRoleMemberCount(FOUNDER_ROLE);
require(balance > 0, 'Nothing to withdraw.');
// 90% split between founders
uint256 founderBalance = (balance * 9) / 10;
for (uint256 i = 0; i < founderCount; i++) {
address member = getRoleMember(FOUNDER_ROLE, i);
_withdraw(member, founderBalance / founderCount);
}
uint256 artistBalance = address(this).balance; // Should be the remaining 10%.
address artist = getRoleMember(ARTIST_ROLE, 0);
_withdraw(artist, artistBalance);
}
/**
* @dev Encapsulates the logic of withdrawing funds from the contract to
* a given address.
*
* @param recipient The address to receive the funds.
* @param amount The amount of funds to be withdrawn.
*/
function _withdraw(address recipient, uint256 amount) private {
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Transfer failed.');
}
}
|
All interfaces need to support `supportsInterface`. This function checks if the provided interface ID is supported. interfaceId The interface ID to check. return True if the interface is supported (AccessControlEnumerable, ERC721, ERC721Enumerable), false otherwise./
|
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC721A)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
| 5,509,817 |
./partial_match/1/0x9Bb0Fc6C1E2ADFaC756a8c9a9A89BB3489B1bd30/sources/AlphaMaster.sol
|
Safe alphapools transfer function, just in case if rounding error causes pool to not have enough APOOL.
|
function safeAPOOLTransfer(address _to, uint _amount) private {
uint apoolBalance = alphapools.balanceOf(address(this));
if (_amount > apoolBalance) {
alphapools.transfer(_to, apoolBalance);
alphapools.transfer(_to, _amount);
}
}
| 9,359,301 |
pragma solidity 0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(address(0) != _newOwner);
newOwner = _newOwner;
}
/**
* @dev Need newOwner to receive the Ownership.
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
newOwner = address(0);
}
}
/**
* @title MultiToken
* @dev The interface of BCZERO Token contract.
*/
contract IBCZEROToken {
function acceptOwnership() public;
function transfer(address _to, uint _value) public returns(bool);
}
/**
* @title BCZEROOwner
* @dev The management contract of BCZEROToken, to manage the ownership of Token contract.
*/
contract BCZEROOwner is Ownable{
IBCZEROToken BCZEROToken;
bool public exchangeEnabled;
address public BCZEROTokenAddr = 0xD45247c07379d94904E0A87b4481F0a1DDfa0C64; // the address of BCZERO Token.
event WithdrawETH(uint256 amount);
event ExchangeEnabledStatus(bool enabled);
/**
* @dev Constructor, setting the contract address of BCZERO token and the owner of this contract.
* setting exchangeEnabled as true.
* @param _owner The owner of this contract.
*/
function BCZEROOwner(address _owner) public {
BCZEROToken = IBCZEROToken(BCZEROTokenAddr);
owner = _owner;
exchangeEnabled = true;
}
/**
* @dev this contract to accept the ownership.
*/
function acceptBCZEROOwnership() public onlyOwner {
BCZEROToken.acceptOwnership();
}
/**
* @dev fallback, Let this contract can receive ETH
*/
function() external payable {
require(exchangeEnabled);
}
/**
* @dev Setting whether the BCZERO tokens can be exchanged.
* @param _enabled true or false
*/
function setExchangeEnabled(bool _enabled) public onlyOwner {
exchangeEnabled = _enabled;
emit ExchangeEnabledStatus(_enabled);
}
/**
* @dev Owner can transfer the ETH of this contract to the owner account by calling this function.
*/
function withdrawETH() public onlyOwner {
uint256 amount = address(this).balance; // getting the balance of this contract(ETH).
require(amount > 0);
owner.transfer(amount); // sending ETH to owner.
emit WithdrawETH(amount);
}
/**
* @dev Owner can transfer the BCZERO token of this contract to the address 'to' by calling this function.
*/
function transferBCZEROToken(address to, uint256 value) public onlyOwner {
BCZEROToken.transfer(to, value);
}
}
|
fallback, Let this contract can receive ETH/
|
function() external payable {
require(exchangeEnabled);
}
| 6,382,625 |
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "./NFTBond.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
/**
* @title ERC20NFTBond
* @dev Contains functions related to buying and liquidating bonds,
* and borrowing and returning funds when the principal is ERC20 token
* @author Ethichub
*/
contract ERC20NFTBond is NFTBond {
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable private principalToken;
IERC20Upgradeable private collateralToken;
struct NFTParams {
string name;
string symbol;
string baseUri;
}
function initialize(
address _principalToken,
address _collateralToken,
NFTParams calldata _nftParams,
address _accessManager,
uint256[] calldata _interests,
uint256[] calldata _maturities
)
external initializer {
principalToken = IERC20Upgradeable(_principalToken);
collateralToken = IERC20Upgradeable(_collateralToken);
__NFTBond_init(_nftParams.name, _nftParams.symbol, _nftParams.baseUri);
__CollateralizedBondGranter_init(_collateralToken);
__InterestParameters_init(_interests, _maturities);
__AccessManaged_init(_accessManager);
}
/**
* @dev External function to buy a bond and returns the tokenId of the bond
* when the contract is active
* @param tokenUri string
* @param beneficiary address
* @param maturity uint256
* @param principal uint256
* @param nftHash bytes32
* @param setApprove bool
* @param nonce uint256
* @param signature bytes
*/
function buyBond(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal,
bytes32 nftHash,
bool setApprove,
uint256 nonce,
bytes memory signature
)
external whenNotPaused returns (uint256) {
return super._buyBond(tokenUri, beneficiary, maturity, principal, nftHash, setApprove, nonce, signature);
}
/**
* @dev External function to redeem a bond and returns the amount of the bond
*/
function redeemBond(uint256 tokenId) external returns (uint256) {
return super._redeemBond(tokenId);
}
function principalTokenAddress() external view returns (address) {
return address(principalToken);
}
function pause() external onlyRole(PAUSER) {
_pause();
}
function unpause() external onlyRole(PAUSER) {
_unpause();
}
/**
* @dev Transfers from the buyer to this contract the principal token amount
*/
function _beforeBondPurchased(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal
)
internal override {
super._beforeBondPurchased(tokenUri, beneficiary, maturity, principal);
principalToken.safeTransferFrom(beneficiary, address(this), principal);
}
/**
* @dev Transfers to the owner of the bond the amount of the bond when the contract has
* liquidity, if not will send the correspondent amount of collateral
*/
function _afterBondRedeemed(
uint256 tokenId,
uint256 amount,
address beneficiary
)
internal override {
Bond memory bond = bonds[tokenId];
super._afterBondRedeemed(tokenId, amount, beneficiary);
if (principalToken.balanceOf(address(this)) < amount) {
uint256 porcentageOfCollateral = 100 - (principalToken.balanceOf(address(this)) * 100 / amount);
uint256 amountOfCollateral = (bond.principal * porcentageOfCollateral / 100) * collateralMultiplier;
principalToken.safeTransfer(beneficiary, principalToken.balanceOf(address(this)));
if (collateralToken.balanceOf(address(this)) < amountOfCollateral) {
collateralToken.safeTransfer(beneficiary, collateralToken.balanceOf(address(this)));
} else {
collateralToken.safeTransfer(beneficiary, amountOfCollateral);
}
} else {
principalToken.safeTransfer(beneficiary, amount);
}
}
/**
* @dev Transfers to the recipient the amount of liquidity available in this contract
*/
function _beforeRequestLiquidity(address destination, uint256 amount) internal override {
principalToken.safeTransfer(destination, amount);
super._beforeRequestLiquidity(destination, amount);
}
/**
* @dev Transfers from the borrower the amount of liquidity borrowed
*/
function _afterReturnLiquidity(address origin, uint256 amount) internal override {
super._afterReturnLiquidity(origin, amount);
principalToken.safeTransferFrom(origin, address(this), amount);
}
function _pause() internal override {
super._pause();
}
function _unpause() internal override {
super._unpause();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "../token/NFT.sol";
import "../bond/CollateralizedBondGranter.sol";
import "../borrowing/LiquidityRequester.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
/**
* @title NFTBond
* @dev Contains functions related to buying and liquidating bonds, and borrowing and returning funds
* @author Ethichub
*/
abstract contract NFTBond is NFT, CollateralizedBondGranter, LiquidityRequester, PausableUpgradeable {
function __NFTBond_init(
string calldata _name,
string calldata _symbol,
string calldata _baseUri
)
internal initializer {
__NFT_init(_name, _symbol, _baseUri);
}
/**
* @dev Returns updated totalBorrowed
* @param origin address of sender
* @param amount uint256 in wei
*/
function returnLiquidity(address origin, uint256 amount) public payable virtual override returns (uint256) {
_beforeReturnLiquidity(origin);
super.returnLiquidity(origin, amount);
_afterReturnLiquidity(origin, amount);
return totalBorrowed;
}
/**
* @dev Requests totalBorrowed
* @param destination address of recipient
* @param amount uint256 in wei
*/
function requestLiquidity(address destination, uint256 amount) public override whenNotPaused returns (uint256) {
_beforeRequestLiquidity(destination, amount);
super.requestLiquidity(destination, amount);
return totalBorrowed;
}
/**
* @dev Returns assigned tokenId of the bond
*/
function _buyBond(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal,
bytes32 nftHash,
bool setApprove,
uint256 nonce,
bytes memory signature
)
internal returns (uint256) {
require(msg.sender == beneficiary, "NFTBond::Beneficiary != sender");
_beforeBondPurchased(tokenUri, beneficiary, maturity, principal);
uint256 tokenId = _safeMintBySig(tokenUri, beneficiary, nftHash, setApprove, nonce, signature);
super._issueBond(tokenId, maturity, principal);
_afterBondPurchased(tokenUri, beneficiary, maturity, principal, tokenId);
return tokenId;
}
/**
* @dev Returns the amunt that corresponds to the bond
*/
function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) {
uint256 amount = super._redeemBond(tokenId);
address beneficiary = ownerOf(tokenId);
_afterBondRedeemed(tokenId, amount, beneficiary);
return amount;
}
function _beforeBondPurchased(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal
) internal virtual {}
function _afterBondPurchased(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal,
uint256 tokenId
) internal virtual {}
function _beforeBondRedeemed(uint256 tokenId, uint256 value) internal virtual {}
function _afterBondRedeemed(uint256 tokenId, uint256 value, address beneficiary) internal virtual {}
function _beforeRequestLiquidity(address destination, uint256 amount) internal virtual {}
function _afterRequestLiquidity(address destination) internal virtual {}
function _beforeReturnLiquidity(address origin) internal virtual {}
function _afterReturnLiquidity(address origin, uint256 amount) internal virtual {}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(IERC20Upgradeable 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: AGPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "../access/AccessManagedUpgradeable.sol";
abstract contract NFT is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable, AccessManagedUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _tokenIdCounter;
string private _baseTokenURI;
mapping(uint256 => bool) private _nonces;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function __NFT_init(
string calldata _name,
string calldata _symbol,
string calldata _baseUri
)
internal initializer {
__ERC721_init(_name, _symbol);
__ERC721Enumerable_init();
__ERC721URIStorage_init();
__ERC721Burnable_init();
__UUPSUpgradeable_init();
_setBaseURI(_baseUri);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function _safeMint(address to, string calldata uri) internal returns (uint256) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
return tokenId;
}
function _safeMintBySig (string calldata uri, address to, bytes32 nftHash, bool setApprove, uint256 nonce, bytes memory signature) internal returns (uint256) {
bytes32 messageHash = keccak256(abi.encode(uri, to, nftHash, address(this), setApprove, nonce, block.chainid));
bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));
(bytes32 r, bytes32 s, uint8 v) = _splitSignature(signature);
address miningSigner = ecrecover(ethSignedMessageHash, v, r, s);
require(_hasRole(MINTER, miningSigner), "NFT::Invalid Signature");
return _safeMint(to, uri);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER)
override
{}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
{
super._burn(tokenId);
}
function _setBaseURI(string calldata _baseUri) private {
_baseTokenURI = _baseUri;
}
function _splitSignature(bytes memory _sig) private pure returns (bytes32 r, bytes32 s, uint8 v) {
require(_sig.length == 65, "Invalid Signature length");
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./BondGranter.sol";
/**
* @title CollateralizedBondGranter
* @dev This contract contains functions related to the emission or withdrawal of
* the bonds with collateral
* @author Ethichub
*/
abstract contract CollateralizedBondGranter is BondGranter {
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable private _collateralToken;
uint256 public collateralMultiplier;
uint256 public totalCollateralizedAmount;
mapping(uint256 => uint256) public collaterals;
event CollateralMultiplierUpdated(uint256 collateralMultiplier);
event CollateralAssigned(uint256 tokenId, uint256 collateralAmount);
event CollateralReleased(uint256 tokenId, uint256 collateralAmount);
event CollateralExcessRemoved(address indexed destination);
function __CollateralizedBondGranter_init(
address collateralToken
)
internal initializer {
collateralMultiplier = 5;
_collateralToken = IERC20Upgradeable(collateralToken);
}
function collateralTokenAddress() external view returns (address) {
return address(_collateralToken);
}
/**
* @dev Sets the number by which the amount of the collateral must be multiplied.
* In this version will be 5
* @param multiplierIndex uint256
*/
function setCollateralMultiplier(uint256 multiplierIndex) external onlyRole(COLLATERAL_BOND_SETTER) {
require(multiplierIndex > 0, "CollateralizedBondGranter::multiplierIndex is 0");
collateralMultiplier = multiplierIndex;
emit CollateralMultiplierUpdated(collateralMultiplier);
}
/**
* @dev Function to withdraw the rest of the collateral that remains in the contract
* to a specified address
* @param destination address
*/
function removeExcessOfCollateral(address destination) external onlyRole(COLLATERAL_BOND_SETTER) {
uint256 excessAmount = _collateralToken.balanceOf(address(this)) - totalCollateralizedAmount;
_collateralToken.safeTransfer(destination, excessAmount);
emit CollateralExcessRemoved(destination);
}
/**
* @dev Issues a bond with calculated collateral
* @param tokenId uint256
* @param maturity uint256 seconds
* @param principal uint256 in wei
*
* Requirement:
*
* - The contract must have enough collateral
*/
function _issueBond(
uint256 tokenId,
uint256 maturity,
uint256 principal
) internal override {
require(_hasCollateral(principal), "CBG::Not enough collateral");
super._issueBond(tokenId, maturity, principal);
uint256 collateralAmount = _calculateCollateralBondAmount(principal);
totalCollateralizedAmount = totalCollateralizedAmount + collateralAmount;
collaterals[tokenId] = collateralAmount;
emit CollateralAssigned(tokenId, collateralAmount);
}
/**
* @dev Updates totalCollateralizedAmount when a bond is redeemed
* @param tokenId uint256
*/
function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) {
uint256 bondValue = super._redeemBond(tokenId);
uint256 collateralAmount = collaterals[tokenId];
totalCollateralizedAmount = totalCollateralizedAmount - collateralAmount;
emit CollateralReleased(tokenId, collateralAmount);
return bondValue;
}
/**
* @dev Returns the amount of collateral that links to the bond
* @param principal uint256
*/
function _calculateCollateralBondAmount(uint256 principal) internal view returns (uint256) {
return principal * collateralMultiplier;
}
/**
* @dev Return true if the balace of the contract minus totalCollateralizedAmount is greater or equal to
* the amount of the bond's collateral
* @param principal uint256
*/
function _hasCollateral(uint256 principal) internal view returns (bool) {
if (_collateralToken.balanceOf(address(this)) - totalCollateralizedAmount >= principal * collateralMultiplier) {
return true;
}
return false;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/ILiquidityRequester.sol";
import "../access/AccessManagedUpgradeable.sol";
import "../Roles.sol";
/**
* @title LiquidityRequester
* @dev Contains functions related to withdraw or return liquidity to the contract for borrowing
* Increments every time money is taking out for lending projects, decrements every time is returned
* @author Ethichub
*/
abstract contract LiquidityRequester is Initializable, ILiquidityRequester, AccessManagedUpgradeable {
uint256 public totalBorrowed;
event LiquidityRequested(uint256 totalBorrowed, address indexed destination);
event LiquidityReturned(uint256 totalBorrowed, address indexed destination);
/**
* @dev External function to withdraw liquidity for borrowing
* @param destination address of recipient
* @param amount uint256 in wei
*
* Requirement:
*
* - Only the role LIQUIDITY_REQUESTER can call this function
*/
function requestLiquidity(address destination, uint256 amount) public virtual override onlyRole(LIQUIDITY_REQUESTER) returns (uint256) {
return _requestLiquidity(destination, amount);
}
/**
* @dev External function to return liquidity from borrowing
* @param origin address of sender
* @param amount uint256 in wei
*/
function returnLiquidity(address origin, uint256 amount) public payable virtual override returns (uint256) {
return _returnLiquidity(origin, amount);
}
/**
* @dev Internal function to withdraw liquidity for borrowing
* Updates and returns totalBorrowed
* @param destination address of recipient
* @param amount uint256 in wei
*/
function _requestLiquidity(address destination, uint256 amount) internal returns (uint256) {
totalBorrowed = totalBorrowed + amount;
emit LiquidityRequested(totalBorrowed, destination);
return totalBorrowed;
}
/**
* @dev Internal function to return liquidity from borrowing
* Updates and returns totalBorrowed
* @param origin address of sender
* @param amount uint256 in wei
*/
function _returnLiquidity(address origin, uint256 amount) internal returns (uint256) {
totalBorrowed = totalBorrowed - amount;
emit LiquidityReturned(totalBorrowed, origin);
return totalBorrowed;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.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);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.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 {}
/**
* @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.
* - `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 tokenId
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.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();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal onlyInitializing {
}
function __ERC721URIStorage_init_unchained() internal onlyInitializing {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate that the this implementation remains valid after an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../Roles.sol";
abstract contract AccessManagedUpgradeable is Initializable {
IAccessControl private _accessControl;
event AccessManagerUpdated(address indexed newAddressManager);
modifier onlyRole(bytes32 role) {
require(_hasRole(role, msg.sender), "AccessManagedUpgradeable::Missing Role");
_;
}
function __AccessManaged_init(address manager) internal initializer {
_accessControl = IAccessControl(manager);
emit AccessManagerUpdated(manager);
}
function setAccessManager(address newManager) public onlyRole(DEFAULT_ADMIN_ROLE) {
_accessControl = IAccessControl(newManager);
emit AccessManagerUpdated(newManager);
}
function _hasRole(bytes32 role, address account) internal view returns (bool) {
return _accessControl.hasRole(role, account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
bytes32 constant DEFAULT_ADMIN_ROLE = bytes32(0);
bytes32 constant INTEREST_PARAMETERS_SETTER = keccak256("INTEREST_PARAMETERS_SETTER");
bytes32 constant COLLATERAL_BOND_SETTER = keccak256("COLLATERAL_BOND_SETTER");
bytes32 constant LIQUIDITY_REQUESTER = keccak256("LIQUIDITY_REQUESTER");
bytes32 constant PAUSER = keccak256("PAUSER");
bytes32 constant UPGRADER = keccak256("UPGRADER");
bytes32 constant MINTER = keccak256("MINTER");
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../utils/InterestCalculator.sol";
import "./InterestParameters.sol";
/**
* @title BondGranter
* @dev This contract contains functions related to the emission or withdrawal of the bonds
* @author Ethichub
*/
abstract contract BondGranter is Initializable, InterestParameters, InterestCalculator {
struct Bond {
uint256 mintingDate;
uint256 maturity;
uint256 principal;
uint256 interest;
bool redeemed;
}
mapping(uint256 => Bond) public bonds;
event BondIssued(uint256 tokenId, uint256 mintingDate, uint256 maturity, uint256 principal, uint256 interest);
event BondRedeemed(uint256 tokenId, uint256 redeemDate, uint256 maturity, uint256 withdrawn, uint256 interest);
/**
* @dev Assigns a bond with its parameters
* @param tokenId uint256
* @param maturity uint256 seconds
* @param principal uint256 in wei
*
* Requirements:
*
* - Principal amount can not be 0
* - Maturity must be greater than the first element of the set of interests
*/
function _issueBond(uint256 tokenId, uint256 maturity, uint256 principal) internal virtual {
require(principal > 0, "BondGranter::Principal is 0");
require(maturity >= maturities[0], "BondGranter::Maturity must be greater than the first interest");
uint256 interest = super.getInterestForMaturity(maturity);
bonds[tokenId] = Bond(block.timestamp, maturity, principal, interest, false);
emit BondIssued(tokenId, block.timestamp, maturity, principal, interest);
}
/**
* @dev Checks eligilibility to redeem the bond and returns its value
* @param tokenId uint256
*/
function _redeemBond(uint256 tokenId) internal virtual returns (uint256) {
Bond memory bond = bonds[tokenId];
require((bond.maturity + bond.mintingDate) < block.timestamp, "BondGranter::Can't redeem yet");
require(!bond.redeemed, "BondGranter::Already redeemed");
bonds[tokenId].redeemed = true;
emit BondRedeemed(tokenId, block.timestamp, bond.maturity, _bondValue(tokenId), bond.interest);
return _bondValue(tokenId);
}
/**
* @dev Returns the actual value of the bond with its interest
* @param tokenId uint256
*/
function _bondValue(uint256 tokenId) internal view virtual returns (uint256) {
Bond memory bond = bonds[tokenId];
return bond.principal + bond.principal * super.simpleInterest(bond.interest, bond.maturity) / 100 / 1000000000000000000;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "../interfaces/IInterestCalculator.sol";
abstract contract InterestCalculator is IInterestCalculator {
function simpleInterest(uint256 interest, uint256 maturity) public view virtual override returns (uint256) {
return _simpleInterest(interest, maturity);
}
function _simpleInterest(uint256 interest, uint256 maturity) internal view virtual returns (uint256) {
return maturity * interest;
}
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IInterestParameters.sol";
import "../access/AccessManagedUpgradeable.sol";
import "../Roles.sol";
/**
* @title InterestParameters
* @dev Contains functions related to interests and maturities for the bonds
* @author Ethichub
*/
abstract contract InterestParameters is Initializable, IInterestParameters, AccessManagedUpgradeable {
uint256[] public interests;
uint256[] public maturities;
uint256 public maxParametersLength;
function __InterestParameters_init(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
internal initializer {
maxParametersLength = 3;
_setInterestParameters(_interests, _maturities);
}
function setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
external override onlyRole(INTEREST_PARAMETERS_SETTER) {
_setInterestParameters(_interests, _maturities);
}
function setMaxInterestParams(uint256 value) external override onlyRole(INTEREST_PARAMETERS_SETTER) {
_setMaxInterestParams(value);
}
function getInterestForMaturity(uint256 maturity) public view override returns (uint256) {
return _getInterestForMaturity(maturity);
}
/**
* @dev Sets the parameters of interests and maturities
* @param _interests set of interests per second in wei
* @param _maturities set of maturities in second
*
* Requirements:
*
* - The length of the array of interests can not be 0
* - The length of the array of interests can not be greater than maxParametersLength
* - The length of the array of interests and maturities must be the same
* - The value of maturities must be in ascending order
* - The values of interest and maturities can not be 0
*/
function _setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
internal {
require(_interests.length > 0, "InterestParameters::Interest must be greater than 0");
require(_interests.length <= maxParametersLength, "InterestParameters::Interest parameters is greater than max parameters");
require(_interests.length == _maturities.length, "InterestParameters::Unequal input length");
for (uint256 i = 0; i < _interests.length; ++i) {
if (i != 0) {
require(_maturities[i-1] < _maturities[i], "InterestParameters::Unordered maturities");
}
require(_interests[i] > 0, "InterestParameters::Can't set zero interest");
require(_maturities[i] > 0, "InterestParameters::Can't set zero maturity");
}
interests = _interests;
maturities = _maturities;
emit InterestParametersSet(interests, maturities);
}
/**
* @dev Sets the maximum length of interests and maturities parameters
* @param value uint256
*
* Requirement:
*
* - The length value can not be 0
*/
function _setMaxInterestParams(uint256 value) internal {
require(value > 0, "InterestParameters::Interest length is 0");
maxParametersLength = value;
emit MaxInterestParametersSet(value);
}
/**
* @dev Checks the interest correspondant to the maturity.
* Needs at least 1 maturity / interest pair.
* Returns interest per second
* @param maturity duration of the bond in seconds
*/
function _getInterestForMaturity(uint256 maturity) internal view returns (uint256) {
require(maturity >= maturities[0], "InterestParameters::Maturity must be greater than first interest");
for (uint256 i = interests.length - 1; i >= 0; --i) {
if (maturity >= maturities[i]) {
return interests[i];
}
}
return interests[0];
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
interface IInterestCalculator {
/**
* @dev Calculates interest per second that is int 1e18
* @param maturity duration of the bond in seconds
* @param interest per second
* @return simple interest per second that is int 1e18
*/
function simpleInterest(uint256 interest, uint256 maturity) external view returns (uint256);
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
interface IInterestParameters {
event InterestParametersSet(uint256[] interests, uint256[] maturities);
event MaxInterestParametersSet(uint256 value);
/**
* Set interests and maturities params, all in seconds
*/
function setInterestParameters(uint256[] calldata interests, uint256[] calldata maturities) external;
function setMaxInterestParams(uint256 value) external;
function getInterestForMaturity(uint256 maturity) external returns (uint256);
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
interface ILiquidityRequester {
/**
* Increments every time money is taking out for lending projects, decrements every time is returned
*/
function requestLiquidity(address destination, uint256 amount) external returns (uint256);
function returnLiquidity(address origin, uint256 amount) external payable returns (uint256);
}
|
Required interface of an ERC721 compliant contract./
|
interface IERC721Upgradeable is IERC165Upgradeable {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 18,923 |
./full_match/4/0x81d2eAc7319919C8d4788b6C50579c75857eaa9D/sources/contracts/multiwrap/Multiwrap.sol
|
Wrap multiple ERC1155, ERC721, ERC20 tokens into a single wrapped NFT.
|
function wrap(
Token[] calldata _tokensToWrap,
string calldata _uriForWrappedToken,
address _recipient
) external payable nonReentrant onlyRoleWithSwitch(MINTER_ROLE) returns (uint256 tokenId) {
if (!hasRole(ASSET_ROLE, address(0))) {
for (uint256 i = 0; i < _tokensToWrap.length; i += 1) {
_checkRole(ASSET_ROLE, _tokensToWrap[i].assetContract);
}
}
tokenId = nextTokenIdToMint;
nextTokenIdToMint += 1;
_storeTokens(_msgSender(), _tokensToWrap, _uriForWrappedToken, tokenId);
_safeMint(_recipient, tokenId);
emit TokensWrapped(_msgSender(), _recipient, tokenId, _tokensToWrap);
}
| 645,995 |
pragma solidity 0.4.20;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function percent(uint value,uint numerator, uint denominator, uint precision) internal pure returns(uint quotient) {
uint _numerator = numerator * 10 ** (precision+1);
uint _quotient = ((_numerator / denominator) + 5) / 10;
return (value*_quotient/1000000000000000000);
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract TREASURE {
/*=====================================
= CONTRACT CONFIGURABLES =
=====================================*/
// Token Details
string public name = "TREASURE";
string public symbol = "TRS";
uint8 constant public decimals = 18;
uint256 constant internal tokenPriceInitial = 0.000000001 ether;
// Token Price Increment & Decrement By 1Gwei
uint256 constant internal tokenPriceIncDec = 0.000000001 ether;
// Proof of Stake (Default at 1 Token)
uint256 public stakingReq = 1e18;
uint256 constant internal magnitude = 2**64;
// Dividend/Distribution Percentage
uint8 constant internal referralFeePercent = 5;
uint8 constant internal dividendFeePercent = 10;
uint8 constant internal tradingFundWalletFeePercent = 10;
uint8 constant internal communityWalletFeePercent = 10;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal sellingWithdrawBalance_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
mapping(address => string) internal contractTokenHolderAddresses;
uint256 internal tokenTotalSupply = 0;
uint256 internal calReferralPercentage = 0;
uint256 internal calDividendPercentage = 0;
uint256 internal calculatedPercentage = 0;
uint256 internal soldTokens = 0;
uint256 internal tempIncomingEther = 0;
uint256 internal tempProfitPerShare = 0;
uint256 internal tempIf = 0;
uint256 internal tempCalculatedDividends = 0;
uint256 internal tempReferall = 0;
uint256 internal tempSellingWithdraw = 0;
uint256 internal profitPerShare_;
// When this is set to true, only ambassadors can purchase tokens
bool public onlyAmbassadors = false;
// Community Wallet Address
address internal constant CommunityWalletAddr = address(0xa6ac94e896fBB8A2c27692e20B301D54D954071E);
// Trading Fund Wallet Address
address internal constant TradingWalletAddr = address(0x40E68DF89cAa6155812225F12907960608A0B9dd);
// Administrator of this contract
mapping(bytes32 => bool) public admin;
/*=================================
= MODIFIERS =
=================================*/
// Only people with tokens
modifier onlybelievers() {
require(myTokens() > 0);
_;
}
// Only people with profits
modifier onlyhodler() {
require(myDividends(true) > 0);
_;
}
// Only people with sold token
modifier onlySelingholder() {
require(sellingWithdrawBalance_[msg.sender] > 0);
_;
}
// Admin can do following things:
// 1. Change the name of contract.
// 2. Change the name of token.
// 3. Change the PoS difficulty .
// Admin CANNOT do following things:
// 1. Take funds out from contract.
// 2. Disable withdrawals.
// 3. Kill the smart contract.
// 4. Change the price of tokens.
modifier onlyAdmin() {
address _adminAddress = msg.sender;
require(admin[keccak256(_adminAddress)]);
_;
}
/*===========================================
= ADMINISTRATOR ONLY FUNCTIONS =
===========================================*/
// Admin can manually disable the ambassador phase
function disableInitialStage() onlyAdmin() public {
onlyAmbassadors = false;
}
function setAdmin(bytes32 _identifier, bool _status) onlyAdmin() public {
admin[_identifier] = _status;
}
function setStakingReq(uint256 _tokensAmount) onlyAdmin() public {
stakingReq = _tokensAmount;
}
function setName(string _tokenName) onlyAdmin() public {
name = _tokenName;
}
function setSymbol(string _tokenSymbol) onlyAdmin() public {
symbol = _tokenSymbol;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase (
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell (
address indexed customerAddress,
uint256 tokensBurned
);
event onReinvestment (
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw (
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onSellingWithdraw (
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event Transfer (
address indexed from,
address indexed to,
uint256 tokens
);
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
function TREASURE() public {
// Contract Admin
admin[0x7cfa1051b7130edfac6eb71d17a849847cf6b7e7ad0b33fad4e124841e5acfbc] = true;
}
// Check contract Ethereum Balance
function totalEthereumBalance() public view returns(uint) {
return this.balance;
}
// Check tokens total supply
function totalSupply() public view returns(uint256) {
return tokenTotalSupply;
}
// Check token balance owned by the caller
function myTokens() public view returns(uint256) {
address ownerAddress = msg.sender;
return tokenBalanceLedger_[ownerAddress];
}
// Check sold tokens
function getSoldTokens() public view returns(uint256) {
return soldTokens;
}
// Check dividends owned by the caller
function myDividends(bool _includeReferralBonus) public view returns(uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
// Check dividend balance of any single address
function dividendsOf(address _customerAddress) view public returns(uint256) {
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
// Check token balance of any address
function balanceOf(address ownerAddress) public view returns(uint256) {
return tokenBalanceLedger_[ownerAddress]; ///need to change
}
// Check Selling Withdraw balance of address
function sellingWithdrawBalance() view public returns(uint256) {
address _customerAddress = msg.sender;
uint256 _sellingWithdraw = (uint256) (sellingWithdrawBalance_[_customerAddress]) ; // Get all balances
return _sellingWithdraw;
}
// Get Buy Price of 1 individual token
function sellPrice() public view returns(uint256) {
if(tokenTotalSupply == 0){
return tokenPriceInitial - tokenPriceIncDec;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum - SafeMath.percent(_ethereum,15,100,18);
}
}
// Get Sell Price of 1 individual token
function buyPrice() public view returns(uint256) {
if(tokenTotalSupply == 0){
return tokenPriceInitial;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
// Converts all of caller's dividends to tokens
function reinvest() onlyhodler() public {
address _customerAddress = msg.sender;
// Get dividends
uint256 _dividends = myDividends(true); // Retrieve Ref. Bonus later in the code
// Calculate 10% for distribution
uint256 TenPercentForDistribution = SafeMath.percent(_dividends,10,100,18);
// Calculate 90% to reinvest into tokens
uint256 NinetyPercentToReinvest = SafeMath.percent(_dividends,90,100,18);
// Dispatch a buy order with the calculatedPercentage
uint256 _tokens = purchaseTokens(NinetyPercentToReinvest, 0x0);
// Empty their all dividends beacuse we are reinvesting them
payoutsTo_[_customerAddress] += (int256) (SafeMath.sub(_dividends, referralBalance_[_customerAddress]) * magnitude);
referralBalance_[_customerAddress] = 0;
// Distribute to all users as per holdings
profitPerShare_ = SafeMath.add(profitPerShare_, (TenPercentForDistribution * magnitude) / tokenTotalSupply);
// Fire Event
onReinvestment(_customerAddress, _dividends, _tokens);
}
// Alias of sell() & withdraw() function
function exit() public {
// Get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
// Withdraw all of the callers earnings
function withdraw() onlyhodler() public {
address _customerAddress = msg.sender;
// Calculate 20% of all Dividends and Transfer them to two communities
uint256 _dividends = myDividends(true); // get all dividends
// Calculate 10% for Trading Wallet
uint256 TenPercentForTradingWallet = SafeMath.percent(_dividends,10,100,18);
// Calculate 10% for Community Wallet
uint256 TenPercentForCommunityWallet= SafeMath.percent(_dividends,10,100,18);
// Update Dividend Tracker
payoutsTo_[_customerAddress] += (int256) (SafeMath.sub(_dividends, referralBalance_[_customerAddress]) * magnitude);
referralBalance_[_customerAddress] = 0;
// Delivery Service
address(CommunityWalletAddr).transfer(TenPercentForCommunityWallet);
// Delivery Service
address(TradingWalletAddr).transfer(TenPercentForTradingWallet);
// Calculate 80% for transfering it to Customer Address
uint256 EightyPercentForCustomer = SafeMath.percent(_dividends,80,100,18);
// Delivery Service
address(_customerAddress).transfer(EightyPercentForCustomer);
// Fire Event
onWithdraw(_customerAddress, _dividends);
}
// Withdraw all sellingWithdraw of the callers earnings
function sellingWithdraw() onlySelingholder() public {
address customerAddress = msg.sender;
uint256 _sellingWithdraw = sellingWithdrawBalance_[customerAddress];
// Empty all sellingWithdraw beacuse we are giving them ETHs
sellingWithdrawBalance_[customerAddress] = 0;
// Delivery Service
address(customerAddress).transfer(_sellingWithdraw);
// Fire Event
onSellingWithdraw(customerAddress, _sellingWithdraw);
}
// Sell Tokens
// Remember there's a 10% fee for sell
function sell(uint256 _amountOfTokens) onlybelievers() public {
address customerAddress = msg.sender;
// Calculate 10% of tokens and distribute them
require(_amountOfTokens <= tokenBalanceLedger_[customerAddress] && _amountOfTokens > 1e18);
uint256 _tokens = SafeMath.sub(_amountOfTokens, 1e18);
uint256 _ethereum = tokensToEthereum_(_tokens);
// Calculate 10% for distribution
uint256 TenPercentToDistribute = SafeMath.percent(_ethereum,10,100,18);
// Calculate 90% for customer withdraw wallet
uint256 NinetyPercentToCustomer = SafeMath.percent(_ethereum,90,100,18);
// Burn Sold Tokens
tokenTotalSupply = SafeMath.sub(tokenTotalSupply, _tokens);
tokenBalanceLedger_[customerAddress] = SafeMath.sub(tokenBalanceLedger_[customerAddress], _tokens);
// Substract sold tokens from circulations of tokenTotalSupply
soldTokens = SafeMath.sub(soldTokens,_tokens);
// Update sellingWithdrawBalance of customer
sellingWithdrawBalance_[customerAddress] += NinetyPercentToCustomer;
// Update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (TenPercentToDistribute * magnitude));
payoutsTo_[customerAddress] -= _updatedPayouts;
// Distribute to all users as per holdings
if (tokenTotalSupply > 0) {
// Update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (TenPercentToDistribute * magnitude) / tokenTotalSupply);
}
// Fire Event
onTokenSell(customerAddress, _tokens);
}
// Transfer tokens from the caller to a new holder
// Remember there's a 5% fee here for transfer
function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers() public returns(bool) {
address customerAddress = msg.sender;
// Make sure user have the requested tokens
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[customerAddress] && _amountOfTokens > 1e18);
// Calculate 5% of total tokens
uint256 FivePercentOfTokens = SafeMath.percent(_amountOfTokens,5,100,18);
// Calculate 95% of total tokens
uint256 NinetyFivePercentOfTokens = SafeMath.percent(_amountOfTokens,95,100,18);
// Burn the fee tokens
// Convert ETH to Tokens
tokenTotalSupply = SafeMath.sub(tokenTotalSupply,FivePercentOfTokens);
// Substract 5% from community of tokens
soldTokens = SafeMath.sub(soldTokens, FivePercentOfTokens);
// Exchange Tokens
tokenBalanceLedger_[customerAddress] = SafeMath.sub(tokenBalanceLedger_[customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], NinetyFivePercentOfTokens) ;
// Calculate value of all token to transfer to ETH
uint256 FivePercentToDistribute = tokensToEthereum_(FivePercentOfTokens);
// Update dividend trackers
payoutsTo_[customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * NinetyFivePercentOfTokens);
// Distribute to all users as per holdings
profitPerShare_ = SafeMath.add(profitPerShare_, (FivePercentToDistribute * magnitude) / tokenTotalSupply);
// Fire Event
Transfer(customerAddress, _toAddress, NinetyFivePercentOfTokens);
return true;
}
// Function to calculate actual value after Taxes
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) {
// Calculate 15% for distribution
uint256 fifteen_percentToDistribute= SafeMath.percent(_ethereumToSpend,15,100,18);
uint256 _dividends = SafeMath.sub(_ethereumToSpend, fifteen_percentToDistribute);
uint256 _amountOfTokens = ethereumToTokens_(_dividends);
return _amountOfTokens;
}
// Function to calculate received ETH
function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) {
require(_tokensToSell <= tokenTotalSupply);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
// Calculate 10% for distribution
uint256 ten_percentToDistribute= SafeMath.percent(_ethereum,10,100,18);
uint256 _dividends = SafeMath.sub(_ethereum, ten_percentToDistribute);
return _dividends;
}
// Convert all incoming ETH to Tokens for the caller and pass down the referral address (if any)
function buy(address referredBy) public payable {
purchaseTokens(msg.value, referredBy);
}
// Fallback function to handle ETH that was sent straight to the contract
// Unfortunately we cannot use a referral address this way.
function() payable public {
purchaseTokens(msg.value, 0x0);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 incomingEthereum, address referredBy) internal returns(uint256) {
// Datasets
address customerAddress = msg.sender;
tempIncomingEther = incomingEthereum;
// Calculate Percentage for Referral (if any)
calReferralPercentage = SafeMath.percent(incomingEthereum,referralFeePercent,100,18);
// Calculate Dividend
calDividendPercentage = SafeMath.percent(incomingEthereum,dividendFeePercent,100,18);
// Calculate remaining amount
calculatedPercentage = SafeMath.percent(incomingEthereum,85,100,18);
// Token will receive against the sent ETH
uint256 _amountOfTokens = ethereumToTokens_(SafeMath.percent(incomingEthereum,85,100,18));
uint256 _dividends = 0;
uint256 minOneToken = 1 * (10 ** decimals);
require(_amountOfTokens > minOneToken && (SafeMath.add(_amountOfTokens,tokenTotalSupply) > tokenTotalSupply));
// If user referred by a Treasure Key
if(
// Is this a referred purchase?
referredBy != 0x0000000000000000000000000000000000000000 &&
// No Cheating!!!!
referredBy != customerAddress &&
// Does the referrer have at least X whole tokens?
tokenBalanceLedger_[referredBy] >= stakingReq
) {
// Give 5 % to Referral User
referralBalance_[referredBy] += SafeMath.percent(incomingEthereum,5,100,18);
_dividends = calDividendPercentage;
} else {
// Add the referral bonus back to the global dividend
_dividends = SafeMath.add(calDividendPercentage, calReferralPercentage);
}
// We can't give people infinite ETH
if(tokenTotalSupply > 0) {
// Add tokens to the pool
tokenTotalSupply = SafeMath.add(tokenTotalSupply, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenTotalSupply));
} else {
// Add tokens to the pool
tokenTotalSupply = _amountOfTokens;
}
// Update circulating supply & the ledger address for the customer
tokenBalanceLedger_[customerAddress] = SafeMath.add(tokenBalanceLedger_[customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[customerAddress] += _updatedPayouts;
// Fire Event
onTokenPurchase(customerAddress, incomingEthereum, _amountOfTokens, referredBy);
// Calculate sold tokens here
soldTokens += _amountOfTokens;
return _amountOfTokens;
}
// Calculate token price based on an amount of incoming ETH
// It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
// Some conversions occurred to prevent decimal errors or underflows/overflows in solidity code.
function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(SqRt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncDec * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncDec)**2)*(tokenTotalSupply**2))
+
(2*(tokenPriceIncDec)*_tokenPriceInitial*tokenTotalSupply)
)
), _tokenPriceInitial
)
)/(tokenPriceIncDec)
)-(tokenTotalSupply);
return _tokensReceived;
}
// Calculate token sell value
// It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
// Some conversions occurred to prevent decimal errors or underflows/overflows in solidity code.
function tokensToEthereum_(uint256 _tokens) public view returns(uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenTotalSupply + 1e18);
uint256 _etherReceived =
(
SafeMath.sub(
(
(
(
tokenPriceInitial + (tokenPriceIncDec * (_tokenSupply/1e18))
)-tokenPriceIncDec
)*(tokens_ - 1e18)
),(tokenPriceIncDec*((tokens_**2-tokens_)/1e18))/2
)/1e18);
return _etherReceived;
}
// This is where all your gas goes
function SqRt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
|
Fallback function to handle ETH that was sent straight to the contract Unfortunately we cannot use a referral address this way.
|
function() payable public {
purchaseTokens(msg.value, 0x0);
}
==========================================*/
| 12,920,308 |
./full_match/1/0x931D8441599B533DfEd618E93Fc32d110543a087/sources/contracts/radiant/staking/MultiFeeDistribution.sol
|
Stake tokens to receive rewards. Locked tokens cannot be withdrawn for defaultLockDuration and are eligible to receive rewards. amount to stake. onBehalfOf address for staking. typeIndex lock type index./
|
function stake(uint256 amount, address onBehalfOf, uint256 typeIndex) external {
_stake(amount, onBehalfOf, typeIndex, false);
}
| 8,422,208 |
pragma solidity ^0.4.24;
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(_beneficiary, _weiAmount);
* require(weiRaised.add(_weiAmount) <= cap);
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract PostDeliveryCrowdsale is TimedCrowdsale {
using SafeMath for uint256;
mapping(address => uint256) public balances;
/**
* @dev Withdraw tokens only after crowdsale ends.
*/
function withdrawTokens() public {
require(hasClosed());
uint256 amount = balances[msg.sender];
require(amount > 0);
balances[msg.sender] = 0;
_deliverTokens(msg.sender, amount);
}
/**
* @dev Overrides parent by storing balances instead of issuing tokens right away.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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
);
}
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
contract Oraclized is Ownable {
address public oracle;
constructor(address _oracle) public {
oracle = _oracle;
}
/**
* @dev Change oracle address
* @param _oracle Oracle address
*/
function setOracle(address _oracle) public onlyOwner {
oracle = _oracle;
}
/**
* @dev Modifier to allow access only by oracle
*/
modifier onlyOracle() {
require(msg.sender == oracle);
_;
}
/**
* @dev Modifier to allow access only by oracle or owner
*/
modifier onlyOwnerOrOracle() {
require((msg.sender == oracle) || (msg.sender == owner));
_;
}
}
contract KYCCrowdsale is Oraclized, PostDeliveryCrowdsale {
using SafeMath for uint256;
/**
* @dev etherPriceInUsd Ether price in cents
* @dev usdRaised Total USD raised while ICO in cents
* @dev weiInvested Stores amount of wei invested by each user
* @dev usdInvested Stores amount of USD invested by each user in cents
*/
uint256 public etherPriceInUsd;
uint256 public usdRaised;
mapping (address => uint256) public weiInvested;
mapping (address => uint256) public usdInvested;
/**
* @dev KYCPassed Registry of users who passed KYC
* @dev KYCRequired Registry of users who has to passed KYC
*/
mapping (address => bool) public KYCPassed;
mapping (address => bool) public KYCRequired;
/**
* @dev KYCRequiredAmountInUsd Amount in cents invested starting from which user must pass KYC
*/
uint256 public KYCRequiredAmountInUsd;
event EtherPriceUpdated(uint256 _cents);
/**
* @param _kycAmountInUsd Amount in cents invested starting from which user must pass KYC
*/
constructor(uint256 _kycAmountInUsd, uint256 _etherPrice) public {
require(_etherPrice > 0);
KYCRequiredAmountInUsd = _kycAmountInUsd;
etherPriceInUsd = _etherPrice;
}
/**
* @dev Update amount required to pass KYC
* @param _cents Amount in cents invested starting from which user must pass KYC
*/
function setKYCRequiredAmount(uint256 _cents) external onlyOwnerOrOracle {
require(_cents > 0);
KYCRequiredAmountInUsd = _cents;
}
/**
* @dev Set ether conversion rate
* @param _cents Price of 1 ETH in cents
*/
function setEtherPrice(uint256 _cents) public onlyOwnerOrOracle {
require(_cents > 0);
etherPriceInUsd = _cents;
emit EtherPriceUpdated(_cents);
}
/**
* @dev Check if KYC is required for address
* @param _address Address to check
*/
function isKYCRequired(address _address) external view returns(bool) {
return KYCRequired[_address];
}
/**
* @dev Check if KYC is passed by address
* @param _address Address to check
*/
function isKYCPassed(address _address) external view returns(bool) {
return KYCPassed[_address];
}
/**
* @dev Check if KYC is not required or passed
* @param _address Address to check
*/
function isKYCSatisfied(address _address) public view returns(bool) {
return !KYCRequired[_address] || KYCPassed[_address];
}
/**
* @dev Returns wei invested by specific amount
* @param _account Account you would like to get wei for
*/
function weiInvestedOf(address _account) external view returns (uint256) {
return weiInvested[_account];
}
/**
* @dev Returns cents invested by specific amount
* @param _account Account you would like to get cents for
*/
function usdInvestedOf(address _account) external view returns (uint256) {
return usdInvested[_account];
}
/**
* @dev Update KYC status for set of addresses
* @param _addresses Addresses to update
* @param _completed Is KYC passed or not
*/
function updateKYCStatus(address[] _addresses, bool _completed) public onlyOwnerOrOracle {
for (uint16 index = 0; index < _addresses.length; index++) {
KYCPassed[_addresses[index]] = _completed;
}
}
/**
* @dev Override update purchasing state
* - update sum of funds invested
* - if total amount invested higher than KYC amount set KYC required to true
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
super._updatePurchasingState(_beneficiary, _weiAmount);
uint256 usdAmount = _weiToUsd(_weiAmount);
usdRaised = usdRaised.add(usdAmount);
usdInvested[_beneficiary] = usdInvested[_beneficiary].add(usdAmount);
weiInvested[_beneficiary] = weiInvested[_beneficiary].add(_weiAmount);
if (usdInvested[_beneficiary] >= KYCRequiredAmountInUsd) {
KYCRequired[_beneficiary] = true;
}
}
/**
* @dev Override token withdraw
* - do not allow token withdraw in case KYC required but not passed
*/
function withdrawTokens() public {
require(isKYCSatisfied(msg.sender));
super.withdrawTokens();
}
/**
* @dev Converts wei to cents
* @param _wei Wei amount
*/
function _weiToUsd(uint256 _wei) internal view returns (uint256) {
return _wei.mul(etherPriceInUsd).div(1e18);
}
/**
* @dev Converts cents to wei
* @param _cents Cents amount
*/
function _usdToWei(uint256 _cents) internal view returns (uint256) {
return _cents.mul(1e18).div(etherPriceInUsd);
}
}
contract KYCRefundableCrowdsale is KYCCrowdsale {
using SafeMath for uint256;
/**
* @dev percentage multiplier to present percentage as decimals. 5 decimal by default
* @dev weiOnFinalize ether balance which was on finalize & will be returned to users in case of failed crowdsale
*/
uint256 private percentage = 100 * 1000;
uint256 private weiOnFinalize;
/**
* @dev goalReached specifies if crowdsale goal is reached
* @dev isFinalized is crowdsale finished
* @dev tokensWithdrawn total amount of tokens already withdrawn
*/
bool public goalReached = false;
bool public isFinalized = false;
uint256 public tokensWithdrawn;
event Refund(address indexed _account, uint256 _amountInvested, uint256 _amountRefunded);
event Finalized();
event OwnerWithdraw(uint256 _amount);
/**
* @dev Set is goal reached or not
* @param _success Is goal reached or not
*/
function setGoalReached(bool _success) external onlyOwner {
require(!isFinalized);
goalReached = _success;
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
*/
function claimRefund() public {
require(isFinalized);
require(!goalReached);
uint256 refundPercentage = _refundPercentage();
uint256 amountInvested = weiInvested[msg.sender];
uint256 amountRefunded = amountInvested.mul(refundPercentage).div(percentage);
weiInvested[msg.sender] = 0;
usdInvested[msg.sender] = 0;
msg.sender.transfer(amountRefunded);
emit Refund(msg.sender, amountInvested, amountRefunded);
}
/**
* @dev Must be called after crowdsale ends, to do some extra finalization works.
*/
function finalize() public onlyOwner {
require(!isFinalized);
// NOTE: We do this because we would like to allow withdrawals earlier than closing time in case of crowdsale success
closingTime = block.timestamp;
weiOnFinalize = address(this).balance;
isFinalized = true;
emit Finalized();
}
/**
* @dev Override. Withdraw tokens only after crowdsale ends.
* Make sure crowdsale is successful & finalized
*/
function withdrawTokens() public {
require(isFinalized);
require(goalReached);
tokensWithdrawn = tokensWithdrawn.add(balances[msg.sender]);
super.withdrawTokens();
}
/**
* @dev Is called by owner to send funds to ICO wallet.
* params _amount Amount to be sent.
*/
function ownerWithdraw(uint256 _amount) external onlyOwner {
require(_amount > 0);
wallet.transfer(_amount);
emit OwnerWithdraw(_amount);
}
/**
* @dev Override. Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
// NOTE: Do nothing here. Keep funds in contract by default
}
/**
* @dev Calculates refund percentage in case some funds will be used by dev team on crowdsale needs
*/
function _refundPercentage() internal view returns (uint256) {
return weiOnFinalize.mul(percentage).div(weiRaised);
}
}
contract AerumCrowdsale is KYCRefundableCrowdsale {
using SafeMath for uint256;
/**
* @dev minInvestmentInUsd Minimal investment allowed in cents
*/
uint256 public minInvestmentInUsd;
/**
* @dev tokensSold Amount of tokens sold by this time
*/
uint256 public tokensSold;
/**
* @dev pledgeTotal Total pledge collected from all investors
* @dev pledgeClosingTime Time when pledge is closed & it's not possible to pledge more or use pledge more
* @dev pledges Mapping of all pledges done by investors
*/
uint256 public pledgeTotal;
uint256 public pledgeClosingTime;
mapping (address => uint256) public pledges;
/**
* @dev whitelistedRate Rate which is used while whitelisted sale (XRM to ETH)
* @dev publicRate Rate which is used white public crowdsale (XRM to ETH)
*/
uint256 public whitelistedRate;
uint256 public publicRate;
event AirDrop(address indexed _account, uint256 _amount);
event MinInvestmentUpdated(uint256 _cents);
event RateUpdated(uint256 _whitelistedRate, uint256 _publicRate);
event Withdraw(address indexed _account, uint256 _amount);
/**
* @param _token ERC20 compatible token on which crowdsale is done
* @param _wallet Address where all ETH funded will be sent after ICO finishes
* @param _whitelistedRate Rate which is used while whitelisted sale
* @param _publicRate Rate which is used white public crowdsale
* @param _openingTime Crowdsale open time
* @param _closingTime Crowdsale close time
* @param _pledgeClosingTime Time when pledge is closed & no more active
\\
* @param _kycAmountInUsd Amount on which KYC will be required in cents
* @param _etherPriceInUsd ETH price in cents
*/
constructor(
ERC20 _token, address _wallet,
uint256 _whitelistedRate, uint256 _publicRate,
uint256 _openingTime, uint256 _closingTime,
uint256 _pledgeClosingTime,
uint256 _kycAmountInUsd, uint256 _etherPriceInUsd)
Oraclized(msg.sender)
Crowdsale(_whitelistedRate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
KYCCrowdsale(_kycAmountInUsd, _etherPriceInUsd)
KYCRefundableCrowdsale()
public {
require(_openingTime < _pledgeClosingTime && _pledgeClosingTime < _closingTime);
pledgeClosingTime = _pledgeClosingTime;
whitelistedRate = _whitelistedRate;
publicRate = _publicRate;
minInvestmentInUsd = 25 * 100;
}
/**
* @dev Update minimal allowed investment
*/
function setMinInvestment(uint256 _cents) external onlyOwnerOrOracle {
minInvestmentInUsd = _cents;
emit MinInvestmentUpdated(_cents);
}
/**
* @dev Update closing time
* @param _closingTime Closing time
*/
function setClosingTime(uint256 _closingTime) external onlyOwner {
require(_closingTime >= openingTime);
closingTime = _closingTime;
}
/**
* @dev Update pledge closing time
* @param _pledgeClosingTime Pledge closing time
*/
function setPledgeClosingTime(uint256 _pledgeClosingTime) external onlyOwner {
require(_pledgeClosingTime >= openingTime && _pledgeClosingTime <= closingTime);
pledgeClosingTime = _pledgeClosingTime;
}
/**
* @dev Update rates
* @param _whitelistedRate Rate which is used while whitelisted sale (XRM to ETH)
* @param _publicRate Rate which is used white public crowdsale (XRM to ETH)
*/
function setRate(uint256 _whitelistedRate, uint256 _publicRate) public onlyOwnerOrOracle {
require(_whitelistedRate > 0);
require(_publicRate > 0);
whitelistedRate = _whitelistedRate;
publicRate = _publicRate;
emit RateUpdated(_whitelistedRate, _publicRate);
}
/**
* @dev Update rates & ether price. Done to not make 2 requests from oracle.
* @param _whitelistedRate Rate which is used while whitelisted sale
* @param _publicRate Rate which is used white public crowdsale
* @param _cents Price of 1 ETH in cents
*/
function setRateAndEtherPrice(uint256 _whitelistedRate, uint256 _publicRate, uint256 _cents) external onlyOwnerOrOracle {
setRate(_whitelistedRate, _publicRate);
setEtherPrice(_cents);
}
/**
* @dev Send remaining tokens back
* @param _to Address to send
* @param _amount Amount to send
*/
function sendTokens(address _to, uint256 _amount) external onlyOwner {
if (!isFinalized || goalReached) {
// NOTE: if crowdsale not finished or successful we should keep at least tokens sold
_ensureTokensAvailable(_amount);
}
token.transfer(_to, _amount);
}
/**
* @dev Get balance fo tokens bought
* @param _address Address of investor
*/
function balanceOf(address _address) external view returns (uint256) {
return balances[_address];
}
/**
* @dev Check if all tokens were sold
*/
function capReached() public view returns (bool) {
return tokensSold >= token.balanceOf(this);
}
/**
* @dev Returns percentage of tokens sold
*/
function completionPercentage() external view returns (uint256) {
uint256 balance = token.balanceOf(this);
if (balance == 0) {
return 0;
}
return tokensSold.mul(100).div(balance);
}
/**
* @dev Returns remaining tokens based on stage
*/
function tokensRemaining() external view returns(uint256) {
return token.balanceOf(this).sub(_tokensLocked());
}
/**
* @dev Override. Withdraw tokens only after crowdsale ends.
* Adding withdraw event
*/
function withdrawTokens() public {
uint256 amount = balances[msg.sender];
super.withdrawTokens();
emit Withdraw(msg.sender, amount);
}
/**
* @dev Override crowdsale pre validate. Check:
* - is amount invested larger than minimal
* - there is enough tokens on balance of contract to proceed
* - check if pledges amount are not more than total coins (in case of pledge period)
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_totalInvestmentInUsd(_beneficiary, _weiAmount) >= minInvestmentInUsd);
_ensureTokensAvailableExcludingPledge(_beneficiary, _getTokenAmount(_weiAmount));
}
/**
* @dev Returns total investment of beneficiary including current one in cents
* @param _beneficiary Address to check
* @param _weiAmount Current amount being invested in wei
*/
function _totalInvestmentInUsd(address _beneficiary, uint256 _weiAmount) internal view returns(uint256) {
return usdInvested[_beneficiary].add(_weiToUsd(_weiAmount));
}
/**
* @dev Override process purchase
* - additionally sum tokens sold
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
super._processPurchase(_beneficiary, _tokenAmount);
tokensSold = tokensSold.add(_tokenAmount);
if (pledgeOpen()) {
// NOTE: In case of buying tokens inside pledge it doesn't matter how we decrease pledge as we change it anyway
_decreasePledge(_beneficiary, _tokenAmount);
}
}
/**
* @dev Decrease pledge of account by specific token amount
* @param _beneficiary Account to increase pledge
* @param _tokenAmount Amount of tokens to decrease pledge
*/
function _decreasePledge(address _beneficiary, uint256 _tokenAmount) internal {
if (pledgeOf(_beneficiary) <= _tokenAmount) {
pledgeTotal = pledgeTotal.sub(pledgeOf(_beneficiary));
pledges[_beneficiary] = 0;
} else {
pledgeTotal = pledgeTotal.sub(_tokenAmount);
pledges[_beneficiary] = pledges[_beneficiary].sub(_tokenAmount);
}
}
/**
* @dev Override to use whitelisted or public crowdsale rates
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 currentRate = getCurrentRate();
return _weiAmount.mul(currentRate);
}
/**
* @dev Returns current XRM to ETH rate based on stage
*/
function getCurrentRate() public view returns (uint256) {
if (pledgeOpen()) {
return whitelistedRate;
}
return publicRate;
}
/**
* @dev Check if pledge period is still open
*/
function pledgeOpen() public view returns (bool) {
return (openingTime <= block.timestamp) && (block.timestamp <= pledgeClosingTime);
}
/**
* @dev Returns amount of pledge for account
*/
function pledgeOf(address _address) public view returns (uint256) {
return pledges[_address];
}
/**
* @dev Check if all tokens were pledged
*/
function pledgeCapReached() public view returns (bool) {
return pledgeTotal.add(tokensSold) >= token.balanceOf(this);
}
/**
* @dev Returns percentage of tokens pledged
*/
function pledgeCompletionPercentage() external view returns (uint256) {
uint256 balance = token.balanceOf(this);
if (balance == 0) {
return 0;
}
return pledgeTotal.add(tokensSold).mul(100).div(balance);
}
/**
* @dev Pledges
* @param _addresses list of addresses
* @param _tokens List of tokens to drop
*/
function pledge(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle {
require(_addresses.length == _tokens.length);
_ensureTokensListAvailable(_tokens);
for (uint16 index = 0; index < _addresses.length; index++) {
pledgeTotal = pledgeTotal.sub(pledges[_addresses[index]]).add(_tokens[index]);
pledges[_addresses[index]] = _tokens[index];
}
}
/**
* @dev Air drops tokens to users
* @param _addresses list of addresses
* @param _tokens List of tokens to drop
*/
function airDropTokens(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle {
require(_addresses.length == _tokens.length);
_ensureTokensListAvailable(_tokens);
for (uint16 index = 0; index < _addresses.length; index++) {
tokensSold = tokensSold.add(_tokens[index]);
balances[_addresses[index]] = balances[_addresses[index]].add(_tokens[index]);
emit AirDrop(_addresses[index], _tokens[index]);
}
}
/**
* @dev Ensure token list total is available
* @param _tokens list of tokens amount
*/
function _ensureTokensListAvailable(uint256[] _tokens) internal {
uint256 total;
for (uint16 index = 0; index < _tokens.length; index++) {
total = total.add(_tokens[index]);
}
_ensureTokensAvailable(total);
}
/**
* @dev Ensure amount of tokens you would like to buy or pledge is available
* @param _tokens Amount of tokens to buy or pledge
*/
function _ensureTokensAvailable(uint256 _tokens) internal view {
require(_tokens.add(_tokensLocked()) <= token.balanceOf(this));
}
/**
* @dev Ensure amount of tokens you would like to buy or pledge is available excluding pledged for account
* @param _account Account which is checked for pledge
* @param _tokens Amount of tokens to buy or pledge
*/
function _ensureTokensAvailableExcludingPledge(address _account, uint256 _tokens) internal view {
require(_tokens.add(_tokensLockedExcludingPledge(_account)) <= token.balanceOf(this));
}
/**
* @dev Returns locked or sold tokens based on stage
*/
function _tokensLocked() internal view returns(uint256) {
uint256 locked = tokensSold.sub(tokensWithdrawn);
if (pledgeOpen()) {
locked = locked.add(pledgeTotal);
}
return locked;
}
/**
* @dev Returns locked or sold tokens based on stage excluding pledged for account
* @param _account Account which is checked for pledge
*/
function _tokensLockedExcludingPledge(address _account) internal view returns(uint256) {
uint256 locked = _tokensLocked();
if (pledgeOpen()) {
locked = locked.sub(pledgeOf(_account));
}
return locked;
}
}
|
Ensure token list total is available _tokens list of tokens amount/
|
function _ensureTokensListAvailable(uint256[] _tokens) internal {
uint256 total;
for (uint16 index = 0; index < _tokens.length; index++) {
total = total.add(_tokens[index]);
}
_ensureTokensAvailable(total);
}
| 889,620 |
/**
*Submitted for verification at Etherscan.io on 2021-03-30
*/
/**
▄▄▄▄▄ ██ █▄▄▄▄ ▄█▄ ████▄ █ ▄▄ ▄ █ ██ ▄▀ ▄ ▄▄▄▄▄
█ ▀▄ █ █ █ ▄▀ █▀ ▀▄ █ █ █ █ █ █ █ █ ▄▀ █ █ ▀▄
▄ ▀▀▀▀▄ █▄▄█ █▀▀▌ █ ▀ █ █ █▀▀▀ ██▀▀█ █▄▄█ █ ▀▄ █ █ ▄ ▀▀▀▀▄
▀▄▄▄▄▀ █ █ █ █ █▄ ▄▀ ▀████ █ █ █ █ █ █ █ █ █ ▀▄▄▄▄▀
█ █ ▀███▀ █ █ █ ███ █▄ ▄█
█ ▀ ▀ ▀ █ ▀▀▀
▀ ▀
*/
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// solhint-disable-next-line compiler-version
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 {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/libraries/Events.sol
pragma solidity ^0.8.0;
/**
* @title A collection of Events
* @notice This library defines all of the Events that the Sarcophagus system
* emits
*/
library Events {
event Creation(address sarcophagusContract);
event RegisterArchaeologist(
address indexed archaeologist,
bytes currentPublicKey,
string endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 bond
);
event UpdateArchaeologist(
address indexed archaeologist,
string endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 addedBond
);
event UpdateArchaeologistPublicKey(
address indexed archaeologist,
bytes currentPublicKey
);
event WithdrawalFreeBond(
address indexed archaeologist,
uint256 withdrawnBond
);
event CreateSarcophagus(
bytes32 indexed identifier,
address indexed archaeologist,
bytes archaeologistPublicKey,
address embalmer,
string name,
uint256 resurrectionTime,
uint256 resurrectionWindow,
uint256 storageFee,
uint256 diggingFee,
uint256 bounty,
bytes recipientPublicKey,
uint256 cursedBond
);
event UpdateSarcophagus(bytes32 indexed identifier, string assetId);
event CancelSarcophagus(bytes32 indexed identifier);
event RewrapSarcophagus(
string assetId,
bytes32 indexed identifier,
uint256 resurrectionTime,
uint256 resurrectionWindow,
uint256 diggingFee,
uint256 bounty,
uint256 cursedBond
);
event UnwrapSarcophagus(
string assetId,
bytes32 indexed identifier,
bytes32 privatekey
);
event AccuseArchaeologist(
bytes32 indexed identifier,
address indexed accuser,
uint256 accuserBondReward,
uint256 embalmerBondReward
);
event BurySarcophagus(bytes32 indexed identifier);
event CleanUpSarcophagus(
bytes32 indexed identifier,
address indexed cleaner,
uint256 cleanerBondReward,
uint256 embalmerBondReward
);
}
// File: contracts/libraries/Types.sol
pragma solidity ^0.8.0;
/**
* @title A collection of defined structs
* @notice This library defines the various data models that the Sarcophagus
* system uses
*/
library Types {
struct Archaeologist {
bool exists;
bytes currentPublicKey;
string endpoint;
address paymentAddress;
uint256 feePerByte;
uint256 minimumBounty;
uint256 minimumDiggingFee;
uint256 maximumResurrectionTime;
uint256 freeBond;
uint256 cursedBond;
}
enum SarcophagusStates {DoesNotExist, Exists, Done}
struct Sarcophagus {
SarcophagusStates state;
address archaeologist;
bytes archaeologistPublicKey;
address embalmer;
string name;
uint256 resurrectionTime;
uint256 resurrectionWindow;
string assetId;
bytes recipientPublicKey;
uint256 storageFee;
uint256 diggingFee;
uint256 bounty;
uint256 currentCursedBond;
bytes32 privateKey;
}
}
// File: contracts/libraries/Datas.sol
pragma solidity ^0.8.0;
/**
* @title A library implementing data structures for the Sarcophagus system
* @notice This library defines a Data struct, which defines all of the state
* that the Sarcophagus system needs to operate. It's expected that a single
* instance of this state will exist.
*/
library Datas {
struct Data {
// archaeologists
address[] archaeologistAddresses;
mapping(address => Types.Archaeologist) archaeologists;
// archaeologist stats
mapping(address => bytes32[]) archaeologistSuccesses;
mapping(address => bytes32[]) archaeologistCancels;
mapping(address => bytes32[]) archaeologistAccusals;
mapping(address => bytes32[]) archaeologistCleanups;
// archaeologist key control
mapping(bytes => bool) archaeologistUsedKeys;
// sarcophaguses
bytes32[] sarcophagusIdentifiers;
mapping(bytes32 => Types.Sarcophagus) sarcophaguses;
// sarcophagus ownerships
mapping(address => bytes32[]) embalmerSarcophaguses;
mapping(address => bytes32[]) archaeologistSarcophaguses;
mapping(address => bytes32[]) recipientSarcophaguses;
}
}
// File: contracts/libraries/Utils.sol
pragma solidity ^0.8.0;
/**
* @title Utility functions used within the Sarcophagus system
* @notice This library implements various functions that are used throughout
* Sarcophagus, mainly to DRY up the codebase
* @dev these functions are all stateless, public, pure/view
*/
library Utils {
/**
* @notice Reverts if the public key length is not exactly 64 bytes long
* @param publicKey the key to check length of
*/
function publicKeyLength(bytes memory publicKey) public pure {
require(publicKey.length == 64, "public key must be 64 bytes");
}
/**
* @notice Reverts if the hash of singleHash does not equal doubleHash
* @param doubleHash the hash to compare hash of singleHash to
* @param singleHash the value to hash and compare against doubleHash
*/
function hashCheck(bytes32 doubleHash, bytes memory singleHash)
public
pure
{
require(doubleHash == keccak256(singleHash), "hashes do not match");
}
/**
* @notice Reverts if the input string is not empty
* @param assetId the string to check
*/
function confirmAssetIdNotSet(string memory assetId) public pure {
require(bytes(assetId).length == 0, "assetId has already been set");
}
/**
* @notice Reverts if existing assetId is not empty, or if new assetId is
* @param existingAssetId the orignal assetId to check, make sure is empty
* @param newAssetId the new assetId, which must not be empty
*/
function assetIdsCheck(
string memory existingAssetId,
string memory newAssetId
) public pure {
// verify that the existingAssetId is currently empty
confirmAssetIdNotSet(existingAssetId);
require(bytes(newAssetId).length > 0, "assetId must not have 0 length");
}
/**
* @notice Reverts if the given data and signature did not come from the
* given address
* @param data the payload which has been signed
* @param v signature element
* @param r signature element
* @param s signature element
* @param account address to confirm data and signature came from
*/
function signatureCheck(
bytes memory data,
uint8 v,
bytes32 r,
bytes32 s,
address account
) public pure {
// generate the address for a given data and signature
address hopefulAddress = ecrecover(keccak256(data), v, r, s);
require(
hopefulAddress == account,
"signature did not come from correct account"
);
}
/**
* @notice Reverts if the given resurrection time is not in the future
* @param resurrectionTime the time to check against block.timestamp
*/
function resurrectionInFuture(uint256 resurrectionTime) public view {
require(
resurrectionTime > block.timestamp,
"resurrection time must be in the future"
);
}
/**
* @notice Calculates the grace period that an archaeologist has after a
* sarcophagus has reached its resurrection time
* @param resurrectionTime the resurrection timestamp of a sarcophagus
* @return the grace period
* @dev The grace period is dependent on how far out the resurrection time
* is. The longer out the resurrection time, the longer the grace period.
* There is a minimum grace period of 30 minutes, otherwise, it's
* calculated as 1% of the time between now and resurrection time.
*/
function getGracePeriod(uint256 resurrectionTime)
public
view
returns (uint256)
{
// set a minimum window of 30 minutes
uint16 minimumResurrectionWindow = 30 minutes;
// calculate 1% of the relative time between now and the resurrection
// time
uint256 gracePeriod = (resurrectionTime - block.timestamp) / 100;
// if our calculated grace period is less than the minimum time, we'll
// use the minimum time instead
if (gracePeriod < minimumResurrectionWindow) {
gracePeriod = minimumResurrectionWindow;
}
// return that grace period
return gracePeriod;
}
/**
* @notice Reverts if we're not within the resurrection window (on either
* side)
* @param resurrectionTime the resurrection time of the sarcophagus
* (absolute, i.e. a date time stamp)
* @param resurrectionWindow the resurrection window of the sarcophagus
* (relative, i.e. "30 minutes")
*/
function unwrapTime(uint256 resurrectionTime, uint256 resurrectionWindow)
public
view
{
// revert if too early
require(
resurrectionTime <= block.timestamp,
"it's not time to unwrap the sarcophagus"
);
// revert if too late
require(
resurrectionTime + resurrectionWindow >= block.timestamp,
"the resurrection window has expired"
);
}
/**
* @notice Reverts if msg.sender is not equal to passed-in address
* @param account the account to verify is msg.sender
*/
function sarcophagusUpdater(address account) public view {
require(
account == msg.sender,
"sarcophagus cannot be updated by account"
);
}
/**
* @notice Reverts if the input resurrection time, digging fee, or bounty
* don't fit within the other given maximum and minimum values
* @param resurrectionTime the resurrection time to check
* @param diggingFee the digging fee to check
* @param bounty the bounty to check
* @param maximumResurrectionTime the maximum resurrection time to check
* against, in relative terms (i.e. "1 year" is 31536000 (seconds))
* @param minimumDiggingFee the minimum digging fee to check against
* @param minimumBounty the minimum bounty to check against
*/
function withinArchaeologistLimits(
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty,
uint256 maximumResurrectionTime,
uint256 minimumDiggingFee,
uint256 minimumBounty
) public view {
// revert if the given resurrection time is too far in the future
require(
resurrectionTime <= block.timestamp + maximumResurrectionTime,
"resurrection time too far in the future"
);
// revert if the given digging fee is too low
require(diggingFee >= minimumDiggingFee, "digging fee is too low");
// revert if the given bounty is too low
require(bounty >= minimumBounty, "bounty is too low");
}
}
// File: contracts/libraries/Archaeologists.sol
pragma solidity ^0.8.0;
/**
* @title A library implementing Archaeologist-specific logic in the
* Sarcophagus system
* @notice This library includes public functions for manipulating
* archaeologists in the Sarcophagus system
*/
library Archaeologists {
/**
* @notice Checks that an archaeologist exists, or doesn't exist, and
* and reverts if necessary
* @param data the system's data struct instance
* @param account the archaeologist address to check existence of
* @param exists bool which flips whether function reverts if archaeologist
* exists or not
*/
function archaeologistExists(
Datas.Data storage data,
address account,
bool exists
) public view {
// set the error message
string memory err = "archaeologist has not been registered yet";
if (!exists) err = "archaeologist has already been registered";
// revert if necessary
require(data.archaeologists[account].exists == exists, err);
}
/**
* @notice Increases internal data structure which tracks free bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to increase free bond by
*/
function increaseFreeBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) private {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// increase the freeBond variable by amount
arch.freeBond = arch.freeBond + amount;
}
/**
* @notice Decreases internal data structure which tracks free bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to decrease free bond by
*/
function decreaseFreeBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) private {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// decrease the free bond variable by amount, reverting if necessary
require(
arch.freeBond >= amount,
"archaeologist does not have enough free bond"
);
arch.freeBond = arch.freeBond - amount;
}
/**
* @notice Increases internal data structure which tracks cursed bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to increase cursed bond by
*/
function increaseCursedBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) private {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// increase the freeBond variable by amount
arch.cursedBond = arch.cursedBond + amount;
}
/**
* @notice Decreases internal data structure which tracks cursed bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to decrease cursed bond by
*/
function decreaseCursedBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) public {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// decrease the free bond variable by amount
arch.cursedBond = arch.cursedBond - amount;
}
/**
* @notice Given an archaeologist and amount, decrease free bond and
* increase cursed bond
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to decrease free bond and increase cursed bond
*/
function lockUpBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) public {
decreaseFreeBond(data, archAddress, amount);
increaseCursedBond(data, archAddress, amount);
}
/**
* @notice Given an archaeologist and amount, increase free bond and
* decrease cursed bond
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to increase free bond and decrease cursed bond
*/
function freeUpBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) public {
increaseFreeBond(data, archAddress, amount);
decreaseCursedBond(data, archAddress, amount);
}
/**
* @notice Calculates and returns the curse for any sarcophagus
* @param diggingFee the digging fee of a sarcophagus
* @param bounty the bounty of a sarcophagus
* @return amount of the curse
* @dev Current implementation simply adds the two inputs together. Future
* strategies should use historical data to build a curve to change this
* amount over time.
*/
function getCursedBond(uint256 diggingFee, uint256 bounty)
public
pure
returns (uint256)
{
// TODO: implment a better algorithm, using some concept of past state
return diggingFee + bounty;
}
/**
* @notice Registers a new archaeologist in the system
* @param data the system's data struct instance
* @param currentPublicKey the public key to be used in the first
* sarcophagus
* @param endpoint where to contact this archaeologist on the internet
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to start with
* @param sarcoToken the SARCO token used for payment handling
* @return index of the new archaeologist
*/
function registerArchaeologist(
Datas.Data storage data,
bytes memory currentPublicKey,
string memory endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond,
IERC20 sarcoToken
) public returns (uint256) {
// verify that the archaeologist does not already exist
archaeologistExists(data, msg.sender, false);
// verify that the public key length is accurate
Utils.publicKeyLength(currentPublicKey);
// transfer SARCO tokens from the archaeologist to this contract, to be
// used as their free bond. can be 0, which indicates that the
// archaeologist is not eligible for any new jobs
if (freeBond > 0) {
sarcoToken.transferFrom(msg.sender, address(this), freeBond);
}
// create a new archaeologist
Types.Archaeologist memory newArch =
Types.Archaeologist({
exists: true,
currentPublicKey: currentPublicKey,
endpoint: endpoint,
paymentAddress: paymentAddress,
feePerByte: feePerByte,
minimumBounty: minimumBounty,
minimumDiggingFee: minimumDiggingFee,
maximumResurrectionTime: maximumResurrectionTime,
freeBond: freeBond,
cursedBond: 0
});
// save the new archaeologist into relevant data structures
data.archaeologists[msg.sender] = newArch;
data.archaeologistAddresses.push(msg.sender);
// emit an event
emit Events.RegisterArchaeologist(
msg.sender,
newArch.currentPublicKey,
newArch.endpoint,
newArch.paymentAddress,
newArch.feePerByte,
newArch.minimumBounty,
newArch.minimumDiggingFee,
newArch.maximumResurrectionTime,
newArch.freeBond
);
// return index of the new archaeologist
return data.archaeologistAddresses.length - 1;
}
/**
* @notice An archaeologist may update their profile
* @param data the system's data struct instance
* @param endpoint where to contact this archaeologist on the internet
* @param newPublicKey the public key to be used in the next
* sarcophagus
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to add to their profile
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the update was successful
*/
function updateArchaeologist(
Datas.Data storage data,
bytes memory newPublicKey,
string memory endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond,
IERC20 sarcoToken
) public returns (bool) {
// verify that the archaeologist exists, and is the sender of this
// transaction
archaeologistExists(data, msg.sender, true);
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[msg.sender];
// if archaeologist is updating their active public key, emit an event
if (keccak256(arch.currentPublicKey) != keccak256(newPublicKey)) {
emit Events.UpdateArchaeologistPublicKey(msg.sender, newPublicKey);
arch.currentPublicKey = newPublicKey;
}
// update the rest of the archaeologist profile
arch.endpoint = endpoint;
arch.paymentAddress = paymentAddress;
arch.feePerByte = feePerByte;
arch.minimumBounty = minimumBounty;
arch.minimumDiggingFee = minimumDiggingFee;
arch.maximumResurrectionTime = maximumResurrectionTime;
// the freeBond variable acts as an incrementer, so only if it's above
// zero will we update their profile variable and transfer the tokens
if (freeBond > 0) {
increaseFreeBond(data, msg.sender, freeBond);
sarcoToken.transferFrom(msg.sender, address(this), freeBond);
}
// emit an event
emit Events.UpdateArchaeologist(
msg.sender,
arch.endpoint,
arch.paymentAddress,
arch.feePerByte,
arch.minimumBounty,
arch.minimumDiggingFee,
arch.maximumResurrectionTime,
freeBond
);
// return true
return true;
}
/**
* @notice Archaeologist can withdraw any of their free bond
* @param data the system's data struct instance
* @param amount the amount of the archaeologist's free bond that they're
* withdrawing
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the withdrawal was successful
*/
function withdrawBond(
Datas.Data storage data,
uint256 amount,
IERC20 sarcoToken
) public returns (bool) {
// verify that the archaeologist exists, and is the sender of this
// transaction
archaeologistExists(data, msg.sender, true);
// move free bond out of the archaeologist
decreaseFreeBond(data, msg.sender, amount);
// transfer the freed SARCOs back to the archaeologist
sarcoToken.transfer(msg.sender, amount);
// emit event
emit Events.WithdrawalFreeBond(msg.sender, amount);
// return true
return true;
}
}
// File: contracts/libraries/PrivateKeys.sol
pragma solidity ^0.8.0;
/**
* @title Private key verification
* @notice Implements a private key -> public key checking function
* @dev modified from https://github.com/1Address/ecsol, removes extra code
* which isn't necessary for our Sarcophagus implementation
*/
library PrivateKeys {
uint256 public constant gx =
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 public constant gy =
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
//
// Based on the original idea of Vitalik Buterin:
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
//
function ecmulVerify(
uint256 x1,
uint256 y1,
bytes32 scalar,
bytes memory pubKey
) private pure returns (bool) {
uint256 m =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
address signer =
ecrecover(
0,
y1 % 2 != 0 ? 28 : 27,
bytes32(x1),
bytes32(mulmod(uint256(scalar), x1, m))
);
address xyAddress =
address(
uint160(
uint256(keccak256(pubKey)) &
0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
)
);
return xyAddress == signer;
}
/**
* @notice Given a private key and a public key, determines if that public
* key was derived from the private key
* @param privKey an secp256k1 private key
* @param pubKey an secp256k1 public key
* @return bool indicating whether the public key is derived from the
* private key
*/
function keyVerification(bytes32 privKey, bytes memory pubKey)
public
pure
returns (bool)
{
return ecmulVerify(gx, gy, privKey, pubKey);
}
}
// File: contracts/libraries/Sarcophaguses.sol
pragma solidity ^0.8.0;
/**
* @title A library implementing Sarcophagus-specific logic in the
* Sarcophagus system
* @notice This library includes public functions for manipulating
* sarcophagi in the Sarcophagus system
*/
library Sarcophaguses {
/**
* @notice Reverts if the given sarcState does not equal the comparison
* state
* @param sarcState the state of a sarcophagus
* @param state the state to compare to
*/
function sarcophagusState(
Types.SarcophagusStates sarcState,
Types.SarcophagusStates state
) internal pure {
// set the error message
string memory error = "sarcophagus already exists";
if (state == Types.SarcophagusStates.Exists)
error = "sarcophagus does not exist or is not active";
// revert if states are not equal
require(sarcState == state, error);
}
/**
* @notice Takes a sarcophagus's cursed bond, splits it in half, and sends
* to the transaction caller and embalmer
* @param data the system's data struct instance
* @param paymentAddress payment address for the transaction caller
* @param sarc the sarcophagus to operate on
* @param sarcoToken the SARCO token used for payment handling
* @return halfToSender the amount of SARCO token going to transaction
* sender
* @return halfToEmbalmer the amount of SARCO token going to embalmer
*/
function splitSend(
Datas.Data storage data,
address paymentAddress,
Types.Sarcophagus storage sarc,
IERC20 sarcoToken
) private returns (uint256, uint256) {
// split the sarcophagus's cursed bond into two halves, taking into
// account solidity math
uint256 halfToEmbalmer = sarc.currentCursedBond / 2;
uint256 halfToSender = sarc.currentCursedBond - halfToEmbalmer;
// transfer the cursed half, plus bounty, plus digging fee to the
// embalmer
sarcoToken.transfer(
sarc.embalmer,
sarc.bounty + sarc.diggingFee + halfToEmbalmer
);
// transfer the other half of the cursed bond to the transaction caller
sarcoToken.transfer(paymentAddress, halfToSender);
// update (decrease) the archaeologist's cursed bond, because this
// sarcophagus is over
Archaeologists.decreaseCursedBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// return data
return (halfToSender, halfToEmbalmer);
}
/**
* @notice Embalmer creates the skeleton for a new sarcopahgus
* @param data the system's data struct instance
* @param name the name of the sarcophagus
* @param archaeologist the address of a registered archaeologist to
* assign this sarcophagus to
* @param resurrectionTime the resurrection time of the sarcophagus
* @param storageFee the storage fee that the archaeologist will receive,
* for saving this sarcophagus on Arweave
* @param diggingFee the digging fee that the archaeologist will receive at
* the first rewrap
* @param bounty the bounty that the archaeologist will receive when the
* sarcophagus is unwrapped
* @param identifier the identifier of the sarcophagus, which is the hash
* of the hash of the inner encrypted layer of the sarcophagus
* @param recipientPublicKey the public key of the recipient
* @param sarcoToken the SARCO token used for payment handling
* @return index of the new sarcophagus
*/
function createSarcophagus(
Datas.Data storage data,
string memory name,
address archaeologist,
uint256 resurrectionTime,
uint256 storageFee,
uint256 diggingFee,
uint256 bounty,
bytes32 identifier,
bytes memory recipientPublicKey,
IERC20 sarcoToken
) public returns (uint256) {
// confirm that the archaeologist exists
Archaeologists.archaeologistExists(data, archaeologist, true);
// confirm that the public key length is correct
Utils.publicKeyLength(recipientPublicKey);
// confirm that this exact sarcophagus does not yet exist
sarcophagusState(
data.sarcophaguses[identifier].state,
Types.SarcophagusStates.DoesNotExist
);
// confirm that the resurrection time is in the future
Utils.resurrectionInFuture(resurrectionTime);
// load the archaeologist
Types.Archaeologist memory arch = data.archaeologists[archaeologist];
// check that the new sarcophagus parameters fit within the selected
// archaeologist's parameters
Utils.withinArchaeologistLimits(
resurrectionTime,
diggingFee,
bounty,
arch.maximumResurrectionTime,
arch.minimumDiggingFee,
arch.minimumBounty
);
// calculate the amount of archaeologist's bond to lock up
uint256 cursedBondAmount =
Archaeologists.getCursedBond(diggingFee, bounty);
// lock up that bond
Archaeologists.lockUpBond(data, archaeologist, cursedBondAmount);
// create a new sarcophagus
Types.Sarcophagus memory sarc =
Types.Sarcophagus({
state: Types.SarcophagusStates.Exists,
archaeologist: archaeologist,
archaeologistPublicKey: arch.currentPublicKey,
embalmer: msg.sender,
name: name,
resurrectionTime: resurrectionTime,
resurrectionWindow: Utils.getGracePeriod(resurrectionTime),
assetId: "",
recipientPublicKey: recipientPublicKey,
storageFee: storageFee,
diggingFee: diggingFee,
bounty: bounty,
currentCursedBond: cursedBondAmount,
privateKey: 0
});
// derive the recipient's address from their public key
address recipientAddress =
address(uint160(uint256(keccak256(recipientPublicKey))));
// save the sarcophagus into necessary data structures
data.sarcophaguses[identifier] = sarc;
data.sarcophagusIdentifiers.push(identifier);
data.embalmerSarcophaguses[msg.sender].push(identifier);
data.archaeologistSarcophaguses[archaeologist].push(identifier);
data.recipientSarcophaguses[recipientAddress].push(identifier);
// transfer digging fee + bounty + storage fee from embalmer to this
// contract
sarcoToken.transferFrom(
msg.sender,
address(this),
diggingFee + bounty + storageFee
);
// emit event with all the data
emit Events.CreateSarcophagus(
identifier,
sarc.archaeologist,
sarc.archaeologistPublicKey,
sarc.embalmer,
sarc.name,
sarc.resurrectionTime,
sarc.resurrectionWindow,
sarc.storageFee,
sarc.diggingFee,
sarc.bounty,
sarc.recipientPublicKey,
sarc.currentCursedBond
);
// return index of the new sarcophagus
return data.sarcophagusIdentifiers.length - 1;
}
/**
* @notice Embalmer updates a sarcophagus given it's identifier, after
* the archaeologist has uploaded the encrypted payload onto Arweave
* @param data the system's data struct instance
* @param newPublicKey the archaeologist's new public key, to use for
* encrypting the next sarcophagus that they're assigned to
* @param identifier the identifier of the sarcophagus
* @param assetId the identifier of the encrypted asset on Arweave
* @param v signature element
* @param r signature element
* @param s signature element
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the update was successful
*/
function updateSarcophagus(
Datas.Data storage data,
bytes memory newPublicKey,
bytes32 identifier,
string memory assetId,
uint8 v,
bytes32 r,
bytes32 s,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the embalmer is making this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// verify that the sarcophagus does not currently have an assetId, and
// that we are setting an actual assetId
Utils.assetIdsCheck(sarc.assetId, assetId);
// verify that the archaeologist's new public key, and the assetId,
// actually came from the archaeologist and were not tampered
Utils.signatureCheck(
abi.encodePacked(newPublicKey, assetId),
v,
r,
s,
sarc.archaeologist
);
// revert if the new public key coming from the archaeologist has
// already been used
require(
!data.archaeologistUsedKeys[sarc.archaeologistPublicKey],
"public key already used"
);
// make sure that the new public key can't be used again in the future
data.archaeologistUsedKeys[sarc.archaeologistPublicKey] = true;
// set the assetId on the sarcophagus
sarc.assetId = assetId;
// load up the archaeologist
Types.Archaeologist storage arch =
data.archaeologists[sarc.archaeologist];
// set the new public key on the archaeologist
arch.currentPublicKey = newPublicKey;
// transfer the storage fee to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.storageFee);
sarc.storageFee = 0;
// emit some events
emit Events.UpdateSarcophagus(identifier, assetId);
emit Events.UpdateArchaeologistPublicKey(
sarc.archaeologist,
arch.currentPublicKey
);
// return true
return true;
}
/**
* @notice An embalmer may cancel a sarcophagus if it hasn't been
* completely created
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the cancel was successful
*/
function cancelSarcophagus(
Datas.Data storage data,
bytes32 identifier,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the asset id has not yet been set
Utils.confirmAssetIdNotSet(sarc.assetId);
// verify that the embalmer is making this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// transfer the bounty and storage fee back to the embalmer
sarcoToken.transfer(sarc.embalmer, sarc.bounty + sarc.storageFee);
// load the archaeologist
Types.Archaeologist memory arch =
data.archaeologists[sarc.archaeologist];
// transfer the digging fee over to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee);
// free up the cursed bond on the archaeologist, because this
// sarcophagus is over
Archaeologists.freeUpBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// set the sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// save the fact that this sarcophagus has been cancelled, against the
// archaeologist
data.archaeologistCancels[sarc.archaeologist].push(identifier);
// emit an event
emit Events.CancelSarcophagus(identifier);
// return true
return true;
}
/**
* @notice Embalmer can extend the resurrection time of the sarcophagus,
* as long as the previous resurrection time is in the future
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param resurrectionTime new resurrection time for the rewrapped
* sarcophagus
* @param diggingFee new digging fee for the rewrapped sarcophagus
* @param bounty new bounty for the rewrapped sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the rewrap was successful
*/
function rewrapSarcophagus(
Datas.Data storage data,
bytes32 identifier,
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the embalmer is making this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// verify that both the current resurrection time, and the new
// resurrection time, are in the future
Utils.resurrectionInFuture(sarc.resurrectionTime);
Utils.resurrectionInFuture(resurrectionTime);
// load the archaeologist
Types.Archaeologist storage arch =
data.archaeologists[sarc.archaeologist];
// check that the sarcophagus updated parameters fit within the
// archaeologist's parameters
Utils.withinArchaeologistLimits(
resurrectionTime,
diggingFee,
bounty,
arch.maximumResurrectionTime,
arch.minimumDiggingFee,
arch.minimumBounty
);
// transfer the new digging fee from embalmer to this contract
sarcoToken.transferFrom(msg.sender, address(this), diggingFee);
// transfer the old digging fee to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee);
// calculate the amount of archaeologist's bond to lock up
uint256 cursedBondAmount =
Archaeologists.getCursedBond(diggingFee, bounty);
// if new cursed bond amount is greater than current cursed bond
// amount, calculate difference and lock it up. if it's less than,
// calculate difference and free it up.
if (cursedBondAmount > sarc.currentCursedBond) {
uint256 diff = cursedBondAmount - sarc.currentCursedBond;
Archaeologists.lockUpBond(data, sarc.archaeologist, diff);
} else if (cursedBondAmount < sarc.currentCursedBond) {
uint256 diff = sarc.currentCursedBond - cursedBondAmount;
Archaeologists.freeUpBond(data, sarc.archaeologist, diff);
}
// determine the new grace period for the archaeologist's final proof
uint256 gracePeriod = Utils.getGracePeriod(resurrectionTime);
// set variarbles on the sarcopahgus
sarc.resurrectionTime = resurrectionTime;
sarc.diggingFee = diggingFee;
sarc.bounty = bounty;
sarc.currentCursedBond = cursedBondAmount;
sarc.resurrectionWindow = gracePeriod;
// emit an event
emit Events.RewrapSarcophagus(
sarc.assetId,
identifier,
resurrectionTime,
gracePeriod,
diggingFee,
bounty,
cursedBondAmount
);
// return true
return true;
}
/**
* @notice Given a sarcophagus identifier, preimage, and private key,
* verify that the data is valid and close out that sarcophagus
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param privateKey the archaeologist's private key which will decrypt the
* @param sarcoToken the SARCO token used for payment handling
* outer layer of the encrypted payload on Arweave
* @return bool indicating that the unwrap was successful
*/
function unwrapSarcophagus(
Datas.Data storage data,
bytes32 identifier,
bytes32 privateKey,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that we're in the resurrection window
Utils.unwrapTime(sarc.resurrectionTime, sarc.resurrectionWindow);
// verify that the given private key derives the public key on the
// sarcophagus
require(
PrivateKeys.keyVerification(
privateKey,
sarc.archaeologistPublicKey
),
"!privateKey"
);
// save that private key onto the sarcophagus model
sarc.privateKey = privateKey;
// load up the archaeologist
Types.Archaeologist memory arch =
data.archaeologists[sarc.archaeologist];
// transfer the Digging fee and bounty over to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee + sarc.bounty);
// free up the archaeologist's cursed bond, because this sarcophagus is
// done
Archaeologists.freeUpBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// set the sarcophagus to Done
sarc.state = Types.SarcophagusStates.Done;
// save this successful sarcophagus against the archaeologist
data.archaeologistSuccesses[sarc.archaeologist].push(identifier);
// emit an event
emit Events.UnwrapSarcophagus(sarc.assetId, identifier, privateKey);
// return true
return true;
}
/**
* @notice Given a sarcophagus, accuse the archaeologist for unwrapping the
* sarcophagus early
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param singleHash the preimage of the sarcophagus identifier
* @param paymentAddress the address to receive payment for accusing the
* archaeologist
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the accusal was successful
*/
function accuseArchaeologist(
Datas.Data storage data,
bytes32 identifier,
bytes memory singleHash,
address paymentAddress,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the resurrection time is in the future
Utils.resurrectionInFuture(sarc.resurrectionTime);
// verify that the accuser has data which proves that the archaeologist
// released the payload too early
Utils.hashCheck(identifier, singleHash);
// reward this transaction's caller, and the embalmer, with the cursed
// bond, and refund the rest of the payment (bounty and digging fees)
// back to the embalmer
(uint256 halfToSender, uint256 halfToEmbalmer) =
splitSend(data, paymentAddress, sarc, sarcoToken);
// save the accusal against the archaeologist
data.archaeologistAccusals[sarc.archaeologist].push(identifier);
// update sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// emit an event
emit Events.AccuseArchaeologist(
identifier,
msg.sender,
halfToSender,
halfToEmbalmer
);
// return true
return true;
}
/**
* @notice Extends a sarcophagus resurrection time into infinity
* effectively signaling that the sarcophagus is over and should never be
* resurrected
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the bury was successful
*/
function burySarcophagus(
Datas.Data storage data,
bytes32 identifier,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the embalmer made this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// verify that the existing resurrection time is in the future
Utils.resurrectionInFuture(sarc.resurrectionTime);
// load the archaeologist
Types.Archaeologist storage arch =
data.archaeologists[sarc.archaeologist];
// free the archaeologist's bond, because this sarcophagus is over
Archaeologists.freeUpBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// transfer the digging fee to the archae
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee);
// set the resurrection time of this sarcopahgus at maxint
sarc.resurrectionTime = 2**256 - 1;
// update sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// emit an event
emit Events.BurySarcophagus(identifier);
// return true
return true;
}
/**
* @notice Clean up a sarcophagus whose resurrection time and window have
* passed. Callable by anyone.
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param paymentAddress the address to receive payment for cleaning up the
* sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the clean up was successful
*/
function cleanUpSarcophagus(
Datas.Data storage data,
bytes32 identifier,
address paymentAddress,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the resurrection window has expired
require(
sarc.resurrectionTime + sarc.resurrectionWindow < block.timestamp,
"sarcophagus resurrection period must be in the past"
);
// reward this transaction's caller, and the embalmer, with the cursed
// bond, and refund the rest of the payment (bounty and digging fees)
// back to the embalmer
(uint256 halfToSender, uint256 halfToEmbalmer) =
splitSend(data, paymentAddress, sarc, sarcoToken);
// save the cleanup against the archaeologist
data.archaeologistCleanups[sarc.archaeologist].push(identifier);
// update sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// emit an event
emit Events.CleanUpSarcophagus(
identifier,
msg.sender,
halfToSender,
halfToEmbalmer
);
// return true
return true;
}
}
// File: contracts/Sarcophagus.sol
pragma solidity ^0.8.0;
/**
* @title The main Sarcophagus system contract
* @notice This contract implements the entire public interface for the
* Sarcophagus system
*
* Sarcophagus implements a Dead Man's Switch using the Ethereum network as
* the official source of truth for the switch (the "sarcophagus"), the Arweave
* blockchain as the data storage layer for the encrypted payload, and a
* decentralized network of secret-holders (the "archaeologists") who are
* responsible for keeping a private key secret until the dead man's switch is
* activated (via inaction by the "embalmer", the creator of the sarcophagus).
*
* @dev All function calls "proxy" down to functions implemented in one of
* many libraries
*/
contract Sarcophagus is Initializable {
// keep a reference to the SARCO token, which is used for payments
// throughout the system
IERC20 public sarcoToken;
// all system data is stored within this single instance (_data) of the
// Data struct
Datas.Data private _data;
/**
* @notice Contract initializer
* @param _sarcoToken The address of the SARCO token
*/
function initialize(address _sarcoToken) public initializer {
sarcoToken = IERC20(_sarcoToken);
emit Events.Creation(_sarcoToken);
}
/**
* @notice Return the number of archaeologists that have been registered
* @return total registered archaeologist count
*/
function archaeologistCount() public view virtual returns (uint256) {
return _data.archaeologistAddresses.length;
}
/**
* @notice Given an index (of the full archaeologist array), return the
* archaeologist address at that index
* @param index The index of the registered archaeologist
* @return address of the archaeologist
*/
function archaeologistAddresses(uint256 index)
public
view
virtual
returns (address)
{
return _data.archaeologistAddresses[index];
}
/**
* @notice Given an archaeologist address, return that archaeologist's
* profile
* @param account The archaeologist account's address
* @return the Archaeologist object
*/
function archaeologists(address account)
public
view
virtual
returns (Types.Archaeologist memory)
{
return _data.archaeologists[account];
}
/**
* @notice Return the total number of sarcophagi that have been created
* @return the number of sarcophagi that have ever been created
*/
function sarcophagusCount() public view virtual returns (uint256) {
return _data.sarcophagusIdentifiers.length;
}
/**
* @notice Return the unique identifier of a sarcophagus, given it's index
* @param index The index of the sarcophagus
* @return the unique identifier of the given sarcophagus
*/
function sarcophagusIdentifier(uint256 index)
public
view
virtual
returns (bytes32)
{
return _data.sarcophagusIdentifiers[index];
}
/**
* @notice Returns the count of sarcophagi created by a specific embalmer
* @param embalmer The address of the given embalmer
* @return the number of sarcophagi which have been created by an embalmer
*/
function embalmerSarcophagusCount(address embalmer)
public
view
virtual
returns (uint256)
{
return _data.embalmerSarcophaguses[embalmer].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given embalmer
* and index
* @param embalmer The address of an embalmer
* @param index The index of the embalmer's list of sarcophagi
* @return the double hash associated with the index of the embalmer's
* sarcophagi
*/
function embalmerSarcophagusIdentifier(address embalmer, uint256 index)
public
view
virtual
returns (bytes32)
{
return _data.embalmerSarcophaguses[embalmer][index];
}
/**
* @notice Returns the count of sarcophagi created for a specific
* archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of sarcophagi which have been created for an
* archaeologist
*/
function archaeologistSarcophagusCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistSarcophaguses[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given
* archaeologist and index
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's list of sarcophagi
* @return the identifier associated with the index of the archaeologist's
* sarcophagi
*/
function archaeologistSarcophagusIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistSarcophaguses[archaeologist][index];
}
/**
* @notice Returns the count of sarcophagi created for a specific recipient
* @param recipient The address of the given recipient
* @return the number of sarcophagi which have been created for a recipient
*/
function recipientSarcophagusCount(address recipient)
public
view
virtual
returns (uint256)
{
return _data.recipientSarcophaguses[recipient].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given recipient
* and index
* @param recipient The address of a recipient
* @param index The index of the recipient's list of sarcophagi
* @return the identifier associated with the index of the recipient's
* sarcophagi
*/
function recipientSarcophagusIdentifier(address recipient, uint256 index)
public
view
virtual
returns (bytes32)
{
return _data.recipientSarcophaguses[recipient][index];
}
/**
* @notice Returns the count of successful sarcophagi completed by the
* archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of sarcophagi which have been successfully completed
* by the archaeologist
*/
function archaeologistSuccessesCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistSuccesses[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given archaeologist
* and index of successful sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's list of successfully
* completed sarcophagi
* @return the identifier associated with the index of the archaeologist's
* successfully completed sarcophagi
*/
function archaeologistSuccessesIdentifier(
address archaeologist,
uint256 index
) public view returns (bytes32) {
return _data.archaeologistSuccesses[archaeologist][index];
}
/**
* @notice Returns the count of cancelled sarcophagi from the archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of cancelled sarcophagi from the archaeologist
*/
function archaeologistCancelsCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistCancels[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given archaeologist
* and index of the cancelled sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's cancelled sarcophagi
* @return the identifier associated with the index of the archaeologist's
* cancelled sarcophagi
*/
function archaeologistCancelsIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistCancels[archaeologist][index];
}
/**
* @notice Returns the count of accused sarcophagi from the archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of accused sarcophagi from the archaeologist
*/
function archaeologistAccusalsCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistAccusals[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given
* archaeologist and index of the accused sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's accused sarcophagi
* @return the identifier associated with the index of the archaeologist's
* accused sarcophagi
*/
function archaeologistAccusalsIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistAccusals[archaeologist][index];
}
/**
* @notice Returns the count of cleaned-up sarcophagi from the
* archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of cleaned-up sarcophagi from the archaeologist
*/
function archaeologistCleanupsCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistCleanups[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given
* archaeologist and index of the cleaned-up sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's accused sarcophagi
* @return the identifier associated with the index of the archaeologist's
* leaned-up sarcophagi
*/
function archaeologistCleanupsIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistCleanups[archaeologist][index];
}
/**
* @notice Returns sarcophagus data given an indentifier
* @param identifier the unique identifier a sarcophagus
* @return sarc the Sarcophagus object
*/
function sarcophagus(bytes32 identifier)
public
view
virtual
returns (Types.Sarcophagus memory)
{
return _data.sarcophaguses[identifier];
}
/**
* @notice Registers a new archaeologist in the system
* @param currentPublicKey the public key to be used in the first
* sarcophagus
* @param endpoint where to contact this archaeologist on the internet
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to start with
* @return index of the new archaeologist
*/
function registerArchaeologist(
bytes memory currentPublicKey,
string memory endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond
) public virtual returns (uint256) {
return
Archaeologists.registerArchaeologist(
_data,
currentPublicKey,
endpoint,
paymentAddress,
feePerByte,
minimumBounty,
minimumDiggingFee,
maximumResurrectionTime,
freeBond,
sarcoToken
);
}
/**
* @notice An archaeologist may update their profile
* @param endpoint where to contact this archaeologist on the internet
* @param newPublicKey the public key to be used in the next
* sarcophagus
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to add to their profile
* @return bool indicating that the update was successful
*/
function updateArchaeologist(
string memory endpoint,
bytes memory newPublicKey,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond
) public virtual returns (bool) {
return
Archaeologists.updateArchaeologist(
_data,
newPublicKey,
endpoint,
paymentAddress,
feePerByte,
minimumBounty,
minimumDiggingFee,
maximumResurrectionTime,
freeBond,
sarcoToken
);
}
/**
* @notice Archaeologist can withdraw any of their free bond
* @param amount the amount of the archaeologist's free bond that they're
* withdrawing
* @return bool indicating that the withdrawal was successful
*/
function withdrawBond(uint256 amount) public virtual returns (bool) {
return Archaeologists.withdrawBond(_data, amount, sarcoToken);
}
/**
* @notice Embalmer creates the skeleton for a new sarcopahgus
* @param name the name of the sarcophagus
* @param archaeologist the address of a registered archaeologist to
* assign this sarcophagus to
* @param resurrectionTime the resurrection time of the sarcophagus
* @param storageFee the storage fee that the archaeologist will receive,
* for saving this sarcophagus on Arweave
* @param diggingFee the digging fee that the archaeologist will receive at
* the first rewrap
* @param bounty the bounty that the archaeologist will receive when the
* sarcophagus is unwrapped
* @param identifier the identifier of the sarcophagus, which is the hash
* of the hash of the inner encrypted layer of the sarcophagus
* @param recipientPublicKey the public key of the recipient
* @return index of the new sarcophagus
*/
function createSarcophagus(
string memory name,
address archaeologist,
uint256 resurrectionTime,
uint256 storageFee,
uint256 diggingFee,
uint256 bounty,
bytes32 identifier,
bytes memory recipientPublicKey
) public virtual returns (uint256) {
return
Sarcophaguses.createSarcophagus(
_data,
name,
archaeologist,
resurrectionTime,
storageFee,
diggingFee,
bounty,
identifier,
recipientPublicKey,
sarcoToken
);
}
/**
* @notice Embalmer updates a sarcophagus given it's identifier, after
* the archaeologist has uploaded the encrypted payload onto Arweave
* @param newPublicKey the archaeologist's new public key, to use for
* encrypting the next sarcophagus that they're assigned to
* @param identifier the identifier of the sarcophagus
* @param assetId the identifier of the encrypted asset on Arweave
* @param v signature element
* @param r signature element
* @param s signature element
* @return bool indicating that the update was successful
*/
function updateSarcophagus(
bytes memory newPublicKey,
bytes32 identifier,
string memory assetId,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (bool) {
return
Sarcophaguses.updateSarcophagus(
_data,
newPublicKey,
identifier,
assetId,
v,
r,
s,
sarcoToken
);
}
/**
* @notice An embalmer may cancel a sarcophagus if it hasn't been
* completely created
* @param identifier the identifier of the sarcophagus
* @return bool indicating that the cancel was successful
*/
function cancelSarcophagus(bytes32 identifier)
public
virtual
returns (bool)
{
return Sarcophaguses.cancelSarcophagus(_data, identifier, sarcoToken);
}
/**
* @notice Embalmer can extend the resurrection time of the sarcophagus,
* as long as the previous resurrection time is in the future
* @param identifier the identifier of the sarcophagus
* @param resurrectionTime new resurrection time for the rewrapped
* sarcophagus
* @param diggingFee new digging fee for the rewrapped sarcophagus
* @param bounty new bounty for the rewrapped sarcophagus
* @return bool indicating that the rewrap was successful
*/
function rewrapSarcophagus(
bytes32 identifier,
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty
) public virtual returns (bool) {
return
Sarcophaguses.rewrapSarcophagus(
_data,
identifier,
resurrectionTime,
diggingFee,
bounty,
sarcoToken
);
}
/**
* @notice Given a sarcophagus identifier, preimage, and private key,
* verify that the data is valid and close out that sarcophagus
* @param identifier the identifier of the sarcophagus
* @param privateKey the archaeologist's private key which will decrypt the
* outer layer of the encrypted payload on Arweave
* @return bool indicating that the unwrap was successful
*/
function unwrapSarcophagus(bytes32 identifier, bytes32 privateKey)
public
virtual
returns (bool)
{
return
Sarcophaguses.unwrapSarcophagus(
_data,
identifier,
privateKey,
sarcoToken
);
}
/**
* @notice Given a sarcophagus, accuse the archaeologist for unwrapping the
* sarcophagus early
* @param identifier the identifier of the sarcophagus
* @param singleHash the preimage of the sarcophagus identifier
* @param paymentAddress the address to receive payment for accusing the
* archaeologist
* @return bool indicating that the accusal was successful
*/
function accuseArchaeologist(
bytes32 identifier,
bytes memory singleHash,
address paymentAddress
) public virtual returns (bool) {
return
Sarcophaguses.accuseArchaeologist(
_data,
identifier,
singleHash,
paymentAddress,
sarcoToken
);
}
/**
* @notice Extends a sarcophagus resurrection time into infinity
* effectively signaling that the sarcophagus is over and should never be
* resurrected
* @param identifier the identifier of the sarcophagus
* @return bool indicating that the bury was successful
*/
function burySarcophagus(bytes32 identifier) public virtual returns (bool) {
return Sarcophaguses.burySarcophagus(_data, identifier, sarcoToken);
}
/**
* @notice Clean up a sarcophagus whose resurrection time and window have
* passed. Callable by anyone.
* @param identifier the identifier of the sarcophagus
* @param paymentAddress the address to receive payment for cleaning up the
* sarcophagus
* @return bool indicating that the clean up was successful
*/
function cleanUpSarcophagus(bytes32 identifier, address paymentAddress)
public
virtual
returns (bool)
{
return
Sarcophaguses.cleanUpSarcophagus(
_data,
identifier,
paymentAddress,
sarcoToken
);
}
}
|
An embalmer may cancel a sarcophagus if it hasn't been completely created data the system's data struct instance identifier the identifier of the sarcophagus sarcoToken the SARCO token used for payment handling return bool indicating that the cancel was successful/ load the sarcophagus, and make sure it exists verify that the asset id has not yet been set verify that the embalmer is making this transaction transfer the bounty and storage fee back to the embalmer load the archaeologist transfer the digging fee over to the archaeologist free up the cursed bond on the archaeologist, because this sarcophagus is over set the sarcophagus state to Done save the fact that this sarcophagus has been cancelled, against the archaeologist emit an event return true
|
function cancelSarcophagus(
Datas.Data storage data,
bytes32 identifier,
IERC20 sarcoToken
) public returns (bool) {
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
Utils.confirmAssetIdNotSet(sarc.assetId);
Utils.sarcophagusUpdater(sarc.embalmer);
sarcoToken.transfer(sarc.embalmer, sarc.bounty + sarc.storageFee);
Types.Archaeologist memory arch =
data.archaeologists[sarc.archaeologist];
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee);
Archaeologists.freeUpBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
sarc.state = Types.SarcophagusStates.Done;
data.archaeologistCancels[sarc.archaeologist].push(identifier);
emit Events.CancelSarcophagus(identifier);
return true;
}
| 2,451,189 |
pragma solidity ^0.4.21;
// File: contracts/Oracle/DSAuth.sol
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
// File: contracts/Oracle/DSMath.sol
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) constant internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) constant internal returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) {
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
function rmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
// File: contracts/Oracle/DSNote.sol
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
// File: contracts/Oracle/DSThing.sol
contract DSThing is DSAuth, DSNote, DSMath {
}
// File: contracts/Oracle/DSValue.sol
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() constant returns (bytes32, bool) {
return (val,has);
}
function read() constant returns (bytes32) {
var (wut, has) = peek();
assert(has);
return wut;
}
function poke(bytes32 wut) note auth {
val = wut;
has = true;
}
function void() note auth { // unset the value
has = false;
}
}
// File: contracts/Oracle/Medianizer.sol
contract Medianizer is DSValue {
mapping (bytes12 => address) public values;
mapping (address => bytes12) public indexes;
bytes12 public next = 0x1;
uint96 public min = 0x1;
function set(address wat) auth {
bytes12 nextId = bytes12(uint96(next) + 1);
assert(nextId != 0x0);
set(next, wat);
next = nextId;
}
function set(bytes12 pos, address wat) note auth {
if (pos == 0x0) throw;
if (wat != 0 && indexes[wat] != 0) throw;
indexes[values[pos]] = 0; // Making sure to remove a possible existing address in that position
if (wat != 0) {
indexes[wat] = pos;
}
values[pos] = wat;
}
function setMin(uint96 min_) note auth {
if (min_ == 0x0) throw;
min = min_;
}
function setNext(bytes12 next_) note auth {
if (next_ == 0x0) throw;
next = next_;
}
function unset(bytes12 pos) {
set(pos, 0);
}
function unset(address wat) {
set(indexes[wat], 0);
}
function poke() {
poke(0);
}
function poke(bytes32) note {
(val, has) = compute();
}
function compute() constant returns (bytes32, bool) {
bytes32[] memory wuts = new bytes32[](uint96(next) - 1);
uint96 ctr = 0;
for (uint96 i = 1; i < uint96(next); i++) {
if (values[bytes12(i)] != 0) {
var (wut, wuz) = DSValue(values[bytes12(i)]).peek();
if (wuz) {
if (ctr == 0 || wut >= wuts[ctr - 1]) {
wuts[ctr] = wut;
} else {
uint96 j = 0;
while (wut >= wuts[j]) {
j++;
}
for (uint96 k = ctr; k > j; k--) {
wuts[k] = wuts[k - 1];
}
wuts[j] = wut;
}
ctr++;
}
}
}
if (ctr < min) return (val, false);
bytes32 value;
if (ctr % 2 == 0) {
uint128 val1 = uint128(wuts[(ctr / 2) - 1]);
uint128 val2 = uint128(wuts[ctr / 2]);
value = bytes32(wdiv(hadd(val1, val2), 2 ether));
} else {
value = wuts[(ctr - 1) / 2];
}
return (value, true);
}
}
// File: contracts/Oracle/PriceFeed.sol
/// price-feed.sol
// Copyright (C) 2017 DappHub, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
contract PriceFeed is DSThing {
uint128 val;
uint32 public zzz;
function peek() public view
returns (bytes32, bool)
{
return (bytes32(val), now < zzz);
}
function read() public view
returns (bytes32)
{
assert(now < zzz);
return bytes32(val);
}
function post(uint128 val_, uint32 zzz_, address med_) public note auth
{
val = val_;
zzz = zzz_;
bool ret = med_.call(bytes4(keccak256("poke()")));
ret;
}
function void() public note auth
{
zzz = 0;
}
}
// File: contracts/Oracle/PriceOracleInterface.sol
/*
This contract is the interface between the MakerDAO priceFeed and our DX platform.
*/
contract PriceOracleInterface {
address public priceFeedSource;
address public owner;
bool public emergencyMode;
event NonValidPriceFeed(address priceFeedSource);
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// @dev constructor of the contract
/// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract
function PriceOracleInterface(
address _owner,
address _priceFeedSource
)
public
{
owner = _owner;
priceFeedSource = _priceFeedSource;
}
/// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will
/// output always a price of 600 USD. This gives everyone time to set up a new pricefeed.
function raiseEmergency(bool _emergencyMode)
public
onlyOwner()
{
emergencyMode = _emergencyMode;
}
/// @dev updates the priceFeedSource
/// @param _owner address of owner
function updateCurator(
address _owner
)
public
onlyOwner()
{
owner = _owner;
}
/// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off
function getUSDETHPrice()
public
returns (uint256)
{
// if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD
if(emergencyMode){
return 600;
}
bytes32 price;
bool valid=true;
(price, valid) = Medianizer(priceFeedSource).peek();
if (!valid) {
NonValidPriceFeed(priceFeedSource);
}
// ensuring that there is no underflow or overflow possible,
// even if the price is compromised
uint priceUint = uint256(price)/(1 ether);
if (priceUint == 0) return 1;
if (priceUint > 1000000) return 1000000;
return priceUint;
}
}
// File: @gnosis.pm/util-contracts/contracts/Math.sol
/// @title Math library - Allows calculation of logarithmic and exponential functions
/// @author Alan Lu - <[email protected]>
/// @author Stefan George - <[email protected]>
library Math {
/*
* Constants
*/
// This is equal to 1 in our calculations
uint public constant ONE = 0x10000000000000000;
uint public constant LN2 = 0xb17217f7d1cf79ac;
uint public constant LOG2_E = 0x171547652b82fe177;
/*
* Public functions
*/
/// @dev Returns natural exponential function value of given x
/// @param x x
/// @return e**x
function exp(int x)
public
pure
returns (uint)
{
// revert if x is > MAX_POWER, where
// MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE))
require(x <= 2454971259878909886679);
// return 0 if exp(x) is tiny, using
// MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE))
if (x < -818323753292969962227)
return 0;
// Transform so that e^x -> 2^x
x = x * int(ONE) / int(LN2);
// 2^x = 2^whole(x) * 2^frac(x)
// ^^^^^^^^^^ is a bit shift
// so Taylor expand on z = frac(x)
int shift;
uint z;
if (x >= 0) {
shift = x / int(ONE);
z = uint(x % int(ONE));
}
else {
shift = x / int(ONE) - 1;
z = ONE - uint(-x % int(ONE));
}
// 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ...
//
// Can generate the z coefficients using mpmath and the following lines
// >>> from mpmath import mp
// >>> mp.dps = 100
// >>> ONE = 0x10000000000000000
// >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7)))
// 0xb17217f7d1cf79ab
// 0x3d7f7bff058b1d50
// 0xe35846b82505fc5
// 0x276556df749cee5
// 0x5761ff9e299cc4
// 0xa184897c363c3
uint zpow = z;
uint result = ONE;
result += 0xb17217f7d1cf79ab * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x3d7f7bff058b1d50 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe35846b82505fc5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x276556df749cee5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x5761ff9e299cc4 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xa184897c363c3 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xffe5fe2c4586 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x162c0223a5c8 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1b5253d395e * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e4cf5158b * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e8cac735 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1c3bd650 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1816193 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x131496 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe1b7 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x9c7 * zpow / ONE;
if (shift >= 0) {
if (result >> (256-shift) > 0)
return (2**256-1);
return result << shift;
}
else
return result >> (-shift);
}
/// @dev Returns natural logarithm value of given x
/// @param x x
/// @return ln(x)
function ln(uint x)
public
pure
returns (int)
{
require(x > 0);
// binary search for floor(log2(x))
int ilog2 = floorLog2(x);
int z;
if (ilog2 < 0)
z = int(x << uint(-ilog2));
else
z = int(x >> uint(ilog2));
// z = x * 2^-⌊log₂x⌋
// so 1 <= z < 2
// and ln z = ln x - ⌊log₂x⌋/log₂e
// so just compute ln z using artanh series
// and calculate ln x from that
int term = (z - int(ONE)) * int(ONE) / (z + int(ONE));
int halflnz = term;
int termpow = term * term / int(ONE) * term / int(ONE);
halflnz += termpow / 3;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 5;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 7;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 9;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 11;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 13;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 15;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 17;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 19;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 21;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 23;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 25;
return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz;
}
/// @dev Returns base 2 logarithm value of given x
/// @param x x
/// @return logarithmic value
function floorLog2(uint x)
public
pure
returns (int lo)
{
lo = -64;
int hi = 193;
// I use a shift here instead of / 2 because it floors instead of rounding towards 0
int mid = (hi + lo) >> 1;
while((lo + 1) < hi) {
if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE)
hi = mid;
else
lo = mid;
mid = (hi + lo) >> 1;
}
}
/// @dev Returns maximum of an array
/// @param nums Numbers to look through
/// @return Maximum number
function max(int[] nums)
public
pure
returns (int maxNum)
{
require(nums.length > 0);
maxNum = -2**255;
for (uint i = 0; i < nums.length; i++)
if (nums[i] > maxNum)
maxNum = nums[i];
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
internal
pure
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
internal
pure
returns (bool)
{
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b)
internal
pure
returns (bool)
{
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToMul(a, b));
return a * b;
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(int a, int b)
internal
pure
returns (bool)
{
return (b >= 0 && a + b >= a) || (b < 0 && a + b < a);
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(int a, int b)
internal
pure
returns (bool)
{
return (b >= 0 && a - b <= a) || (b < 0 && a - b > a);
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(int a, int b)
internal
pure
returns (bool)
{
return (b == 0) || (a * b / b == a);
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(int a, int b)
internal
pure
returns (int)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(int a, int b)
internal
pure
returns (int)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(int a, int b)
internal
pure
returns (int)
{
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/util-contracts/contracts/Proxy.sol
/// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy.
/// @author Alan Lu - <[email protected]>
contract Proxied {
address public masterCopy;
}
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
contract Proxy is Proxied {
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
function Proxy(address _masterCopy)
public
{
require(_masterCopy != 0);
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function ()
external
payable
{
address _masterCopy = masterCopy;
assembly {
calldatacopy(0, 0, calldatasize())
let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch success
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
// File: @gnosis.pm/util-contracts/contracts/Token.sol
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
pragma solidity ^0.4.21;
/// @title Abstract token contract - Functions to be implemented by token contracts
contract Token {
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/*
* Public functions
*/
function transfer(address to, uint value) public returns (bool);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
function balanceOf(address owner) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function totalSupply() public view returns (uint);
}
// File: @gnosis.pm/util-contracts/contracts/StandardToken.sol
contract StandardTokenData {
/*
* Storage
*/
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowances;
uint totalTokens;
}
/// @title Standard token contract with overflow protection
contract StandardToken is Token, StandardTokenData {
using Math for *;
/*
* Public functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transfer(address to, uint value)
public
returns (bool)
{
if ( !balances[msg.sender].safeToSub(value)
|| !balances[to].safeToAdd(value))
return false;
balances[msg.sender] -= value;
balances[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success
/// @param from Address from where tokens are withdrawn
/// @param to Address to where tokens are sent
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
if ( !balances[from].safeToSub(value)
|| !allowances[from][msg.sender].safeToSub(value)
|| !balances[to].safeToAdd(value))
return false;
balances[from] -= value;
allowances[from][msg.sender] -= value;
balances[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success
/// @param spender Address of allowed account
/// @param value Number of approved tokens
/// @return Was approval successful?
function approve(address spender, uint value)
public
returns (bool)
{
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Returns number of allowed tokens for given address
/// @param owner Address of token owner
/// @param spender Address of token spender
/// @return Remaining allowance for spender
function allowance(address owner, address spender)
public
view
returns (uint)
{
return allowances[owner][spender];
}
/// @dev Returns number of tokens owned by given address
/// @param owner Address of token owner
/// @return Balance of owner
function balanceOf(address owner)
public
view
returns (uint)
{
return balances[owner];
}
/// @dev Returns total supply of tokens
/// @return Total supply
function totalSupply()
public
view
returns (uint)
{
return totalTokens;
}
}
// File: contracts/TokenFRT.sol
/// @title Standard token contract with overflow protection
contract TokenFRT is StandardToken {
string public constant symbol = "MGN";
string public constant name = "Magnolia Token";
uint8 public constant decimals = 18;
struct unlockedToken {
uint amountUnlocked;
uint withdrawalTime;
}
/*
* Storage
*/
address public owner;
address public minter;
// user => unlockedToken
mapping (address => unlockedToken) public unlockedTokens;
// user => amount
mapping (address => uint) public lockedTokenBalances;
/*
* Public functions
*/
function TokenFRT(
address _owner
)
public
{
require(_owner != address(0));
owner = _owner;
}
// @dev allows to set the minter of Magnolia tokens once.
// @param _minter the minter of the Magnolia tokens, should be the DX-proxy
function updateMinter(
address _minter
)
public
{
require(msg.sender == owner);
require(_minter != address(0));
minter = _minter;
}
// @dev the intention is to set the owner as the DX-proxy, once it is deployed
// Then only an update of the DX-proxy contract after a 30 days delay could change the minter again.
function updateOwner(
address _owner
)
public
{
require(msg.sender == owner);
require(_owner != address(0));
owner = _owner;
}
function mintTokens(
address user,
uint amount
)
public
{
require(msg.sender == minter);
lockedTokenBalances[user] = add(lockedTokenBalances[user], amount);
totalTokens = add(totalTokens, amount);
}
/// @dev Lock Token
function lockTokens(
uint amount
)
public
returns (uint totalAmountLocked)
{
// Adjust amount by balance
amount = min(amount, balances[msg.sender]);
// Update state variables
balances[msg.sender] = sub(balances[msg.sender], amount);
lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], amount);
// Get return variable
totalAmountLocked = lockedTokenBalances[msg.sender];
}
function unlockTokens(
uint amount
)
public
returns (uint totalAmountUnlocked, uint withdrawalTime)
{
// Adjust amount by locked balances
amount = min(amount, lockedTokenBalances[msg.sender]);
if (amount > 0) {
// Update state variables
lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount);
unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount);
unlockedTokens[msg.sender].withdrawalTime = now + 24 hours;
}
// Get return variables
totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked;
withdrawalTime = unlockedTokens[msg.sender].withdrawalTime;
}
function withdrawUnlockedTokens()
public
{
require(unlockedTokens[msg.sender].withdrawalTime < now);
balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked);
unlockedTokens[msg.sender].amountUnlocked = 0;
}
function min(uint a, uint b)
public
pure
returns (uint)
{
if (a < b) {
return a;
} else {
return b;
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
public
constant
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
public
constant
returns (bool)
{
return a >= b;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
public
constant
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
public
constant
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
}
// File: @gnosis.pm/owl-token/contracts/TokenOWL.sol
contract TokenOWL is Proxied, StandardToken {
using Math for *;
string public constant name = "OWL Token";
string public constant symbol = "OWL";
uint8 public constant decimals = 18;
struct masterCopyCountdownType {
address masterCopy;
uint timeWhenAvailable;
}
masterCopyCountdownType masterCopyCountdown;
address public creator;
address public minter;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed from, address indexed user, uint256 amount);
modifier onlyCreator() {
// R1
require(msg.sender == creator);
_;
}
/// @dev trickers the update process via the proxyMaster for a new address _masterCopy
/// updating is only possible after 30 days
function startMasterCopyCountdown (
address _masterCopy
)
public
onlyCreator()
{
require(address(_masterCopy) != 0);
// Update masterCopyCountdown
masterCopyCountdown.masterCopy = _masterCopy;
masterCopyCountdown.timeWhenAvailable = now + 30 days;
}
/// @dev executes the update process via the proxyMaster for a new address _masterCopy
function updateMasterCopy()
public
onlyCreator()
{
require(address(masterCopyCountdown.masterCopy) != 0);
require(now >= masterCopyCountdown.timeWhenAvailable);
// Update masterCopy
masterCopy = masterCopyCountdown.masterCopy;
}
function getMasterCopy()
public
view
returns (address)
{
return masterCopy;
}
/// @dev Set minter. Only the creator of this contract can call this.
/// @param newMinter The new address authorized to mint this token
function setMinter(address newMinter)
public
onlyCreator()
{
minter = newMinter;
}
/// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this.
/// @param newOwner The new address, which should become the owner
function setNewOwner(address newOwner)
public
onlyCreator()
{
creator = newOwner;
}
/// @dev Mints OWL.
/// @param to Address to which the minted token will be given
/// @param amount Amount of OWL to be minted
function mintOWL(address to, uint amount)
public
{
require(minter != 0 && msg.sender == minter);
balances[to] = balances[to].add(amount);
totalTokens = totalTokens.add(amount);
emit Minted(to, amount);
}
/// @dev Burns OWL.
/// @param user Address of OWL owner
/// @param amount Amount of OWL to be burnt
function burnOWL(address user, uint amount)
public
{
allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount);
balances[user] = balances[user].sub(amount);
totalTokens = totalTokens.sub(amount);
emit Burnt(msg.sender, user, amount);
}
}
// File: contracts/DutchExchange.sol
/// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction
/// @author Alex Herrmann - <[email protected]>
/// @author Dominik Teiml - <[email protected]>
contract DutchExchange is Proxied {
// The price is a rational number, so we need a concept of a fraction
struct fraction {
uint num;
uint den;
}
uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours;
uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes;
uint constant WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE = 30 days;
uint constant AUCTION_START_WAITING_FOR_FUNDING = 1;
address public newMasterCopy;
// Time when new masterCopy is updatabale
uint public masterCopyCountdown;
// > Storage
// auctioneer has the power to manage some variables
address public auctioneer;
// Ether ERC-20 token
address public ethToken;
// Price Oracle interface
PriceOracleInterface public ethUSDOracle;
// Price Oracle interface proposals during update process
PriceOracleInterface public newProposalEthUSDOracle;
uint public oracleInterfaceCountdown;
// Minimum required sell funding for adding a new token pair, in USD
uint public thresholdNewTokenPair;
// Minimum required sell funding for starting antoher auction, in USD
uint public thresholdNewAuction;
// Fee reduction token (magnolia, ERC-20 token)
TokenFRT public frtToken;
// Token for paying fees
TokenOWL public owlToken;
// mapping that stores the tokens, which are approved
// Token => approved
// Only tokens approved by auctioneer generate frtToken tokens
mapping (address => bool) public approvedTokens;
// For the following two mappings, there is one mapping for each token pair
// The order which the tokens should be called is smaller, larger
// These variables should never be called directly! They have getters below
// Token => Token => index
mapping (address => mapping (address => uint)) public latestAuctionIndices;
// Token => Token => time
mapping (address => mapping (address => uint)) public auctionStarts;
// Token => Token => auctionIndex => price
mapping (address => mapping (address => mapping (uint => fraction))) public closingPrices;
// Token => Token => amount
mapping (address => mapping (address => uint)) public sellVolumesCurrent;
// Token => Token => amount
mapping (address => mapping (address => uint)) public sellVolumesNext;
// Token => Token => amount
mapping (address => mapping (address => uint)) public buyVolumes;
// Token => user => amount
// balances stores a user's balance in the DutchX
mapping (address => mapping (address => uint)) public balances;
// Token => Token => auctionIndex => amount
mapping (address => mapping (address => mapping (uint => uint))) public extraTokens;
// Token => Token => auctionIndex => user => amount
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public sellerBalances;
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public buyerBalances;
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public claimedAmounts;
// > Modifiers
modifier onlyAuctioneer() {
// Only allows auctioneer to proceed
// R1
require(msg.sender == auctioneer);
_;
}
/// @dev Constructor-Function creates exchange
/// @param _frtToken - address of frtToken ERC-20 token
/// @param _owlToken - address of owlToken ERC-20 token
/// @param _auctioneer - auctioneer for managing interfaces
/// @param _ethToken - address of ETH ERC-20 token
/// @param _ethUSDOracle - address of the oracle contract for fetching feeds
/// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD
function setupDutchExchange(
TokenFRT _frtToken,
TokenOWL _owlToken,
address _auctioneer,
address _ethToken,
PriceOracleInterface _ethUSDOracle,
uint _thresholdNewTokenPair,
uint _thresholdNewAuction
)
public
{
// Make sure contract hasn't been initialised
require(ethToken == 0);
// Validates inputs
require(address(_owlToken) != address(0));
require(address(_frtToken) != address(0));
require(_auctioneer != 0);
require(_ethToken != 0);
require(address(_ethUSDOracle) != address(0));
frtToken = _frtToken;
owlToken = _owlToken;
auctioneer = _auctioneer;
ethToken = _ethToken;
ethUSDOracle = _ethUSDOracle;
thresholdNewTokenPair = _thresholdNewTokenPair;
thresholdNewAuction = _thresholdNewAuction;
}
function updateAuctioneer(
address _auctioneer
)
public
onlyAuctioneer
{
require(_auctioneer != address(0));
auctioneer = _auctioneer;
}
function initiateEthUsdOracleUpdate(
PriceOracleInterface _ethUSDOracle
)
public
onlyAuctioneer
{
require(address(_ethUSDOracle) != address(0));
newProposalEthUSDOracle = _ethUSDOracle;
oracleInterfaceCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE);
NewOracleProposal(_ethUSDOracle);
}
function updateEthUSDOracle()
public
onlyAuctioneer
{
require(address(newProposalEthUSDOracle) != address(0));
require(oracleInterfaceCountdown < now);
ethUSDOracle = newProposalEthUSDOracle;
newProposalEthUSDOracle = PriceOracleInterface(0);
}
function updateThresholdNewTokenPair(
uint _thresholdNewTokenPair
)
public
onlyAuctioneer
{
thresholdNewTokenPair = _thresholdNewTokenPair;
}
function updateThresholdNewAuction(
uint _thresholdNewAuction
)
public
onlyAuctioneer
{
thresholdNewAuction = _thresholdNewAuction;
}
function updateApprovalOfToken(
address[] token,
bool approved
)
public
onlyAuctioneer
{
for(uint i = 0; i < token.length; i++) {
approvedTokens[token[i]] = approved;
Approval(token[i], approved);
}
}
function startMasterCopyCountdown (
address _masterCopy
)
public
onlyAuctioneer
{
require(_masterCopy != address(0));
// Update masterCopyCountdown
newMasterCopy = _masterCopy;
masterCopyCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE);
NewMasterCopyProposal(_masterCopy);
}
function updateMasterCopy()
public
onlyAuctioneer
{
require(newMasterCopy != address(0));
require(now >= masterCopyCountdown);
// Update masterCopy
masterCopy = newMasterCopy;
newMasterCopy = address(0);
}
/// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator
/// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator
function addTokenPair(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
uint initialClosingPriceNum,
uint initialClosingPriceDen
)
public
{
// R1
require(token1 != token2);
// R2
require(initialClosingPriceNum != 0);
// R3
require(initialClosingPriceDen != 0);
// R4
require(getAuctionIndex(token1, token2) == 0);
// R5: to prevent overflow
require(initialClosingPriceNum < 10 ** 18);
// R6
require(initialClosingPriceDen < 10 ** 18);
setAuctionIndex(token1, token2);
token1Funding = min(token1Funding, balances[token1][msg.sender]);
token2Funding = min(token2Funding, balances[token2][msg.sender]);
// R7
require(token1Funding < 10 ** 30);
// R8
require(token2Funding < 10 ** 30);
uint fundedValueUSD;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// Compute fundedValueUSD
address ethTokenMem = ethToken;
if (token1 == ethTokenMem) {
// C1
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token1Funding, ethUSDPrice);
} else if (token2 == ethTokenMem) {
// C2
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token2Funding, ethUSDPrice);
} else {
// C3: Neither token is ethToken
fundedValueUSD = calculateFundedValueTokenToken(token1, token2,
token1Funding, token2Funding, ethTokenMem, ethUSDPrice);
}
// R5
require(fundedValueUSD >= thresholdNewTokenPair);
// Save prices of opposite auctions
closingPrices[token1][token2][0] = fraction(initialClosingPriceNum, initialClosingPriceDen);
closingPrices[token2][token1][0] = fraction(initialClosingPriceDen, initialClosingPriceNum);
// Split into two fns because of 16 local-var cap
addTokenPairSecondPart(token1, token2, token1Funding, token2Funding);
}
function calculateFundedValueTokenToken(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
address ethTokenMem,
uint ethUSDPrice
)
internal
view
returns (uint fundedValueUSD)
{
// We require there to exist ethToken-Token auctions
// R3.1
require(getAuctionIndex(token1, ethTokenMem) > 0);
// R3.2
require(getAuctionIndex(token2, ethTokenMem) > 0);
// Price of Token 1
uint priceToken1Num;
uint priceToken1Den;
(priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1);
// Price of Token 2
uint priceToken2Num;
uint priceToken2Den;
(priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2);
// Compute funded value in ethToken and USD
// 10^30 * 10^30 = 10^60
uint fundedValueETH = add(mul(token1Funding, priceToken1Num) / priceToken1Den,
token2Funding * priceToken2Num / priceToken2Den);
fundedValueUSD = mul(fundedValueETH, ethUSDPrice);
}
function addTokenPairSecondPart(
address token1,
address token2,
uint token1Funding,
uint token2Funding
)
internal
{
balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding);
balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding);
// Fee mechanism, fees are added to extraTokens
uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding);
uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding);
// Update other variables
sellVolumesCurrent[token1][token2] = token1FundingAfterFee;
sellVolumesCurrent[token2][token1] = token2FundingAfterFee;
sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee;
sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee;
setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR);
NewTokenPair(token1, token2);
}
function deposit(
address tokenAddress,
uint amount
)
public
returns (uint)
{
// R1
require(Token(tokenAddress).transferFrom(msg.sender, this, amount));
uint newBal = add(balances[tokenAddress][msg.sender], amount);
balances[tokenAddress][msg.sender] = newBal;
NewDeposit(tokenAddress, amount);
return newBal;
}
function withdraw(
address tokenAddress,
uint amount
)
public
returns (uint)
{
uint usersBalance = balances[tokenAddress][msg.sender];
amount = min(amount, usersBalance);
// R1
require(amount > 0);
// R2
require(Token(tokenAddress).transfer(msg.sender, amount));
uint newBal = sub(usersBalance, amount);
balances[tokenAddress][msg.sender] = newBal;
NewWithdrawal(tokenAddress, amount);
return newBal;
}
function postSellOrder(
address sellToken,
address buyToken,
uint auctionIndex,
uint amount
)
public
returns (uint, uint)
{
// Note: if a user specifies auctionIndex of 0, it
// means he is agnostic which auction his sell order goes into
amount = min(amount, balances[sellToken][msg.sender]);
// R1
require(amount > 0);
// R2
uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken);
require(latestAuctionIndex > 0);
// R3
uint auctionStart = getAuctionStart(sellToken, buyToken);
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1: We are in the 10 minute buffer period
// OR waiting for an auction to receive sufficient sellVolume
// Auction has already cleared, and index has been incremented
// sell order must use that auction index
// R1.1
if (auctionIndex == 0) {
auctionIndex = latestAuctionIndex;
} else {
require(auctionIndex == latestAuctionIndex);
}
// R1.2
require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30);
} else {
// C2
// R2.1: Sell orders must go to next auction
if (auctionIndex == 0) {
auctionIndex = latestAuctionIndex + 1;
} else {
require(auctionIndex == latestAuctionIndex + 1);
}
// R2.2
require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30);
}
// Fee mechanism, fees are added to extraTokens
uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount);
// Update variables
balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount);
uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal;
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1
uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken];
sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee);
} else {
// C2
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee);
}
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING) {
scheduleNextAuction(sellToken, buyToken);
}
NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
return (auctionIndex, newSellerBal);
}
function postBuyOrder(
address sellToken,
address buyToken,
uint auctionIndex,
uint amount
)
public
returns (uint)
{
// R1: auction must not have cleared
require(closingPrices[sellToken][buyToken][auctionIndex].den == 0);
uint auctionStart = getAuctionStart(sellToken, buyToken);
// R2
require(auctionStart <= now);
// R4
require(auctionIndex == getAuctionIndex(sellToken, buyToken));
// R5: auction must not be in waiting period
require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING);
// R6: auction must be funded
require(sellVolumesCurrent[sellToken][buyToken] > 0);
uint buyVolume = buyVolumes[sellToken][buyToken];
amount = min(amount, balances[buyToken][msg.sender]);
// R7
require(add(buyVolume, amount) < 10 ** 30);
// Overbuy is when a part of a buy order clears an auction
// In that case we only process the part before the overbuy
// To calculate overbuy, we first get current price
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
uint amountAfterFee;
if (amount < outstandingVolume) {
if (amount > 0) {
amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount);
}
} else {
amount = outstandingVolume;
amountAfterFee = outstandingVolume;
}
// Here we could also use outstandingVolume or amountAfterFee, it doesn't matter
if (amount > 0) {
// Update variables
balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount);
uint newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal;
buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee);
NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
}
// Checking for equality would suffice here. nevertheless:
if (amount >= outstandingVolume) {
// Clear auction
clearAuction(sellToken, buyToken, auctionIndex, sellVolume);
}
return (newBuyerBal);
}
function claimSellerFunds(
address sellToken,
address buyToken,
address user,
uint auctionIndex
)
public
// < (10^60, 10^61)
returns (uint returned, uint frtsIssued)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user];
// R1
require(sellerBalance > 0);
// Get closing price for said auction
fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
uint num = closingPrice.num;
uint den = closingPrice.den;
// R2: require auction to have cleared
require(den > 0);
// Calculate return
// < 10^30 * 10^30 = 10^60
returned = mul(sellerBalance, num) / den;
frtsIssued = issueFrts(sellToken, buyToken, returned, auctionIndex, sellerBalance, user);
// Claim tokens
sellerBalances[sellToken][buyToken][auctionIndex][user] = 0;
if (returned > 0) {
balances[buyToken][user] = add(balances[buyToken][user], returned);
}
NewSellerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued);
}
function claimBuyerFunds(
address sellToken,
address buyToken,
address user,
uint auctionIndex
)
public
returns (uint returned, uint frtsIssued)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint num;
uint den;
(returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex);
if (closingPrices[sellToken][buyToken][auctionIndex].den == 0) {
// Auction is running
claimedAmounts[sellToken][buyToken][auctionIndex][user] = add(claimedAmounts[sellToken][buyToken][auctionIndex][user], returned);
} else {
// Auction has closed
// We DON'T want to check for returned > 0, because that would fail if a user claims
// intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens)
// Assign extra sell tokens (this is possible only after auction has cleared,
// because buyVolume could still increase before that)
uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex];
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// closingPrices.num represents buyVolume
// < 10^30 * 10^30 = 10^60
uint tokensExtra = mul(buyerBalance, extraTokensTotal) / closingPrices[sellToken][buyToken][auctionIndex].num;
returned = add(returned, tokensExtra);
frtsIssued = issueFrts(buyToken, sellToken, mul(buyerBalance, den) / num, auctionIndex, buyerBalance, user);
// Auction has closed
// Reset buyerBalances and claimedAmounts
buyerBalances[sellToken][buyToken][auctionIndex][user] = 0;
claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0;
}
// Claim tokens
if (returned > 0) {
balances[sellToken][user] = add(balances[sellToken][user], returned);
}
NewBuyerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued);
}
function issueFrts(
address primaryToken,
address secondaryToken,
uint x,
uint auctionIndex,
uint bal,
address user
)
internal
returns (uint frtsIssued)
{
if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) {
address ethTokenMem = ethToken;
// Get frts issued based on ETH price of returned tokens
if (primaryToken == ethTokenMem) {
frtsIssued = bal;
} else if (secondaryToken == ethTokenMem) {
// 10^30 * 10^39 = 10^66
frtsIssued = x;
} else {
// Neither token is ethToken, so we use getHhistoricalPriceOracle()
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1);
// 10^30 * 10^35 = 10^65
frtsIssued = mul(bal, pastNum) / pastDen;
}
if (frtsIssued > 0) {
// Issue frtToken
frtToken.mintTokens(user, frtsIssued);
}
}
}
//@dev allows to close possible theoretical closed markets
//@param sellToken sellToken of an auction
//@param buyToken buyToken of an auction
//@param index is the auctionIndex of the auction
function closeTheoreticalClosedAuction(
address sellToken,
address buyToken,
uint auctionIndex
)
public
{
if(auctionIndex == getAuctionIndex(buyToken, sellToken) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) {
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
if(outstandingVolume == 0) {
postBuyOrder(sellToken, buyToken, auctionIndex, 0);
}
}
}
/// @dev Claim buyer funds for one auction
function getUnclaimedBuyerFunds(
address sellToken,
address buyToken,
address user,
uint auctionIndex
)
public
view
// < (10^67, 10^37)
returns (uint unclaimedBuyerFunds, uint num, uint den)
{
// R1: checks if particular auction has ever run
require(auctionIndex <= getAuctionIndex(sellToken, buyToken));
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
if (num == 0) {
// This should rarely happen - as long as there is >= 1 buy order,
// auction will clear before price = 0. So this is just fail-safe
unclaimedBuyerFunds = 0;
} else {
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// < 10^30 * 10^37 = 10^67
unclaimedBuyerFunds = atleastZero(int(
mul(buyerBalance, den) / num -
claimedAmounts[sellToken][buyToken][auctionIndex][user]
));
}
}
function settleFee(
address primaryToken,
address secondaryToken,
uint auctionIndex,
uint amount
)
internal
// < 10^30
returns (uint amountAfterFee)
{
uint feeNum;
uint feeDen;
(feeNum, feeDen) = getFeeRatio(msg.sender);
// 10^30 * 10^3 / 10^4 = 10^29
uint fee = mul(amount, feeNum) / feeDen;
if (fee > 0) {
fee = settleFeeSecondPart(primaryToken, fee);
uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1];
extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee);
Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee);
}
amountAfterFee = sub(amount, fee);
}
function settleFeeSecondPart(
address primaryToken,
uint fee
)
internal
returns (uint newFee)
{
// Allow user to reduce up to half of the fee with owlToken
uint num;
uint den;
(num, den) = getPriceOfTokenInLastAuction(primaryToken);
// Convert fee to ETH, then USD
// 10^29 * 10^30 / 10^30 = 10^29
uint feeInETH = mul(fee, num) / den;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// 10^29 * 10^6 = 10^35
// Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD
uint feeInUSD = mul(feeInETH, ethUSDPrice);
uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, this), feeInUSD / 2);
amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned);
if (amountOfowlTokenBurned > 0) {
owlToken.burnOWL(msg.sender, amountOfowlTokenBurned);
// Adjust fee
// 10^35 * 10^29 = 10^64
uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD;
newFee = sub(fee, adjustment);
} else {
newFee = fee;
}
}
function getFeeRatio(
address user
)
public
view
// feeRatio < 10^4
returns (uint num, uint den)
{
uint t = frtToken.totalSupply();
uint b = frtToken.lockedTokenBalances(user);
if (b * 100000 < t || t == 0) {
// 0.5%
num = 1;
den = 200;
} else if (b * 10000 < t) {
// 0.4%
num = 1;
den = 250;
} else if (b * 1000 < t) {
// 0.3%
num = 3;
den = 1000;
} else if (b * 100 < t) {
// 0.2%
num = 1;
den = 500;
} else if (b * 10 < t) {
// 0.1%
num = 1;
den = 1000;
} else {
// 0%
num = 0;
den = 1;
}
}
/// @dev clears an Auction
/// @param sellToken sellToken of the auction
/// @param buyToken buyToken of the auction
/// @param auctionIndex of the auction to be cleared.
function clearAuction(
address sellToken,
address buyToken,
uint auctionIndex,
uint sellVolume
)
internal
{
// Get variables
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken];
uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den;
uint auctionStart = getAuctionStart(sellToken, buyToken);
// Update closing price
if (sellVolume > 0) {
closingPrices[sellToken][buyToken][auctionIndex] = fraction(buyVolume, sellVolume);
}
// if (opposite is 0 auction OR price = 0 OR opposite auction cleared)
// price = 0 happens if auction pair has been running for >= 24 hrs = 86400
if (sellVolumeOpp == 0 || now >= auctionStart + 86400 || closingPriceOppDen > 0) {
// Close auction pair
uint buyVolumeOpp = buyVolumes[buyToken][sellToken];
if (closingPriceOppDen == 0 && sellVolumeOpp > 0) {
// Save opposite price
closingPrices[buyToken][sellToken][auctionIndex] = fraction(buyVolumeOpp, sellVolumeOpp);
}
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken];
// Update state variables for both auctions
sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext;
if (sellVolumeNext > 0) {
sellVolumesNext[sellToken][buyToken] = 0;
}
if (buyVolume > 0) {
buyVolumes[sellToken][buyToken] = 0;
}
sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp;
if (sellVolumeNextOpp > 0) {
sellVolumesNext[buyToken][sellToken] = 0;
}
if (buyVolumeOpp > 0) {
buyVolumes[buyToken][sellToken] = 0;
}
// Increment auction index
setAuctionIndex(sellToken, buyToken);
// Check if next auction can be scheduled
scheduleNextAuction(sellToken, buyToken);
}
AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex);
}
function scheduleNextAuction(
address sellToken,
address buyToken
)
internal
{
// Check if auctions received enough sell orders
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
uint sellNum;
uint sellDen;
(sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken);
uint buyNum;
uint buyDen;
(buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken);
// We use current sell volume, because in clearAuction() we set
// sellVolumesCurrent = sellVolumesNext before calling this function
// (this is so that we don't need case work,
// since it might also be called from postSellOrder())
// < 10^30 * 10^31 * 10^6 = 10^67
uint sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen;
uint sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen;
if (sellVolume >= thresholdNewAuction || sellVolumeOpp >= thresholdNewAuction) {
// Schedule next auction
setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION);
} else {
resetAuctionStart(sellToken, buyToken);
}
}
//@ dev returns price in units [token2]/[token1]
//@ param token1 first token for price calculation
//@ param token2 second token for price calculation
//@ param auctionIndex index for the auction to get the averaged price from
function getPriceInPastAuction(
address token1,
address token2,
uint auctionIndex
)
public
view
// price < 10^31
returns (uint num, uint den)
{
if (token1 == token2) {
// C1
num = 1;
den = 1;
} else {
// C2
// R2.1
require(auctionIndex >= 0);
// C3
// R3.1
require(auctionIndex <= getAuctionIndex(token1, token2));
// auction still running
uint i = 0;
bool correctPair = false;
fraction memory closingPriceToken1;
fraction memory closingPriceToken2;
while (!correctPair) {
closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i];
closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i];
if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 ||
closingPriceToken2.num > 0 && closingPriceToken2.den > 0)
{
correctPair = true;
}
i++;
}
// At this point at least one closing price is strictly positive
// If only one is positive, we want to output that
if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) {
num = closingPriceToken2.den;
den = closingPriceToken2.num;
} else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) {
num = closingPriceToken1.num;
den = closingPriceToken1.den;
} else {
// If both prices are positive, output weighted average
num = closingPriceToken2.den + closingPriceToken1.num;
den = closingPriceToken2.num + closingPriceToken1.den;
}
}
}
/// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network
/// @param token address of ERC-20 token
/// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume
function getPriceOfTokenInLastAuction(
address token
)
public
view
// price < 10^31
returns (uint num, uint den)
{
uint latestAuctionIndex = getAuctionIndex(token, ethToken);
// getPriceInPastAuction < 10^30
(num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1);
}
function getCurrentAuctionPrice(
address sellToken,
address buyToken,
uint auctionIndex
)
public
view
// price < 10^37
returns (uint num, uint den)
{
fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
if (closingPrice.den != 0) {
// Auction has closed
(num, den) = (closingPrice.num, closingPrice.den);
} else if (auctionIndex > getAuctionIndex(sellToken, buyToken)) {
(num, den) = (0, 0);
} else {
// Auction is running
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1);
// If we're calling the function into an unstarted auction,
// it will return the starting price of that auction
uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken)));
// The numbers below are chosen such that
// P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0
// 10^5 * 10^31 = 10^36
num = atleastZero(int((86400 - timeElapsed) * pastNum));
// 10^6 * 10^31 = 10^37
den = mul((timeElapsed + 43200), pastDen);
if (mul(num, sellVolumesCurrent[sellToken][buyToken]) <= mul(den, buyVolumes[sellToken][buyToken])) {
num = buyVolumes[sellToken][buyToken];
den = sellVolumesCurrent[sellToken][buyToken];
}
}
}
function depositAndSell(
address sellToken,
address buyToken,
uint amount
)
external
returns (uint newBal, uint auctionIndex, uint newSellerBal)
{
newBal = deposit(sellToken, amount);
(auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount);
}
function claimAndWithdraw(
address sellToken,
address buyToken,
address user,
uint auctionIndex,
uint amount
)
external
returns (uint returned, uint frtsIssued, uint newBal)
{
(returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex);
newBal = withdraw(buyToken, amount);
}
// > Helper fns
function getTokenOrder(
address token1,
address token2
)
public
pure
returns (address, address)
{
if (token2 < token1) {
(token1, token2) = (token2, token1);
}
return (token1, token2);
}
function setAuctionStart(
address token1,
address token2,
uint value
)
internal
{
(token1, token2) = getTokenOrder(token1, token2);
uint auctionStart = now + value;
uint auctionIndex = latestAuctionIndices[token1][token2];
auctionStarts[token1][token2] = auctionStart;
AuctionStartScheduled(token1, token2, auctionIndex, auctionStart);
}
function resetAuctionStart(
address token1,
address token2
)
internal
{
(token1, token2) = getTokenOrder(token1, token2);
if (auctionStarts[token1][token2] != AUCTION_START_WAITING_FOR_FUNDING) {
auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING;
}
}
function getAuctionStart(
address token1,
address token2
)
public
view
returns (uint auctionStart)
{
(token1, token2) = getTokenOrder(token1, token2);
auctionStart = auctionStarts[token1][token2];
}
function setAuctionIndex(
address token1,
address token2
)
internal
{
(token1, token2) = getTokenOrder(token1, token2);
latestAuctionIndices[token1][token2] += 1;
}
function getAuctionIndex(
address token1,
address token2
)
public
view
returns (uint auctionIndex)
{
(token1, token2) = getTokenOrder(token1, token2);
auctionIndex = latestAuctionIndices[token1][token2];
}
// > Math fns
function min(uint a, uint b)
public
pure
returns (uint)
{
if (a < b) {
return a;
} else {
return b;
}
}
function atleastZero(int a)
public
pure
returns (uint)
{
if (a < 0) {
return 0;
} else {
return uint(a);
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
public
pure
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
public
pure
returns (bool)
{
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b)
public
pure
returns (bool)
{
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
public
pure
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
public
pure
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b)
public
pure
returns (uint)
{
require(safeToMul(a, b));
return a * b;
}
function getRunningTokenPairs(
address[] tokens
)
external
view
returns (address[] tokens1, address[] tokens2)
{
uint arrayLength;
for (uint k = 0; k < tokens.length - 1; k++) {
for (uint l = k + 1; l < tokens.length; l++) {
if (getAuctionIndex(tokens[k], tokens[l]) > 0) {
arrayLength++;
}
}
}
tokens1 = new address[](arrayLength);
tokens2 = new address[](arrayLength);
uint h;
for (uint i = 0; i < tokens.length - 1; i++) {
for (uint j = i + 1; j < tokens.length; j++) {
if (getAuctionIndex(tokens[i], tokens[j]) > 0) {
tokens1[h] = tokens[i];
tokens2[h] = tokens[j];
h++;
}
}
}
}
//@dev for quick overview of possible sellerBalances to calculate the possible withdraw tokens
//@param auctionSellToken is the sellToken defining an auctionPair
//@param auctionBuyToken is the buyToken defining an auctionPair
//@param user is the user who wants to his tokens
//@param lastNAuctions how many auctions will be checked. 0 means all
//@returns returns sellbal for all indices for all tokenpairs
function getIndicesWithClaimableTokensForSellers(
address auctionSellToken,
address auctionBuyToken,
address user,
uint lastNAuctions
)
external
view
returns(uint[] indices, uint[] usersBalances)
{
uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken);
uint arrayLength;
uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1;
for (uint j = startingIndex; j <= runningAuctionIndex; j++) {
if (sellerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) {
arrayLength++;
}
}
indices = new uint[](arrayLength);
usersBalances = new uint[](arrayLength);
uint k;
for (uint i = startingIndex; i <= runningAuctionIndex; i++) {
if (sellerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) {
indices[k] = i;
usersBalances[k] = sellerBalances[auctionSellToken][auctionBuyToken][i][user];
k++;
}
}
}
//@dev for quick overview of current sellerBalances for a user
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param user is the user who wants to his tokens
function getSellerBalancesOfCurrentAuctions(
address[] auctionSellTokens,
address[] auctionBuyTokens,
address user
)
external
view
returns (uint[])
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint[] memory sellersBalances = new uint[](length);
for (uint i = 0; i < length; i++) {
uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]);
sellersBalances[i] = sellerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user];
}
return sellersBalances;
}
//@dev for quick overview of possible buyerBalances to calculate the possible withdraw tokens
//@param auctionSellToken is the sellToken defining an auctionPair
//@param auctionBuyToken is the buyToken defining an auctionPair
//@param user is the user who wants to his tokens
//@param lastNAuctions how many auctions will be checked. 0 means all
//@returns returns sellbal for all indices for all tokenpairs
function getIndicesWithClaimableTokensForBuyers(
address auctionSellToken,
address auctionBuyToken,
address user,
uint lastNAuctions
)
external
view
returns(uint[] indices, uint[] usersBalances)
{
uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken);
uint arrayLength;
uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1;
for (uint j = startingIndex; j <= runningAuctionIndex; j++) {
if (buyerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) {
arrayLength++;
}
}
indices = new uint[](arrayLength);
usersBalances = new uint[](arrayLength);
uint k;
for (uint i = startingIndex; i <= runningAuctionIndex; i++) {
if (buyerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) {
indices[k] = i;
usersBalances[k] = buyerBalances[auctionSellToken][auctionBuyToken][i][user];
k++;
}
}
}
//@dev for quick overview of current sellerBalances for a user
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param user is the user who wants to his tokens
function getBuyerBalancesOfCurrentAuctions(
address[] auctionSellTokens,
address[] auctionBuyTokens,
address user
)
external
view
returns (uint[])
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint[] memory buyersBalances = new uint[](length);
for (uint i = 0; i < length; i++) {
uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]);
buyersBalances[i] = buyerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user];
}
return buyersBalances;
}
//@dev for quick overview of approved Tokens
//@param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved
function getApprovedAddressesOfList(
address[] addressToCheck
)
external
view
returns (bool[])
{
uint length = addressToCheck.length;
bool[] memory isApproved = new bool[](length);
for (uint i = 0; i < length; i++) {
isApproved[i] = approvedTokens[addressToCheck[i]];
}
return isApproved;
}
//@dev for multiple withdraws
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param auctionIndices are the auction indices on which an token should be claimedAmounts
//@param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsSeller(
address[] auctionSellTokens,
address[] auctionBuyTokens,
uint[] auctionIndices,
address user
)
external
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint length3 = auctionIndices.length;
require(length2 == length3);
for (uint i = 0; i < length; i++)
claimSellerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]);
}
//@dev for multiple withdraws
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param auctionIndices are the auction indices on which an token should be claimedAmounts
//@param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsBuyer(
address[] auctionSellTokens,
address[] auctionBuyTokens,
uint[] auctionIndices,
address user
)
external
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint length3 = auctionIndices.length;
require(length2 == length3);
for (uint i = 0; i < length; i++)
claimBuyerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]);
}
function getMasterCopy()
external
view
returns (address)
{
return masterCopy;
}
// > Events
event NewDeposit(
address indexed token,
uint amount
);
event NewOracleProposal(
PriceOracleInterface priceOracleInterface
);
event NewMasterCopyProposal(
address newMasterCopy
);
event NewWithdrawal(
address indexed token,
uint amount
);
event NewSellOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewBuyOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewSellerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewBuyerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewTokenPair(
address indexed sellToken,
address indexed buyToken
);
event AuctionCleared(
address indexed sellToken,
address indexed buyToken,
uint sellVolume,
uint buyVolume,
uint indexed auctionIndex
);
event Approval(
address indexed token,
bool approved
);
event AuctionStartScheduled(
address indexed sellToken,
address indexed buyToken,
uint indexed auctionIndex,
uint auctionStart
);
event Fee(
address indexed primaryToken,
address indexed secondarToken,
address indexed user,
uint auctionIndex,
uint fee
);
}
|
for quick overview of current sellerBalances for a user auctionSellTokens are the sellTokens defining an auctionPair auctionBuyTokens are the buyTokens defining an auctionPair user is the user who wants to his tokens
|
function getBuyerBalancesOfCurrentAuctions(
address[] auctionSellTokens,
address[] auctionBuyTokens,
address user
)
external
view
returns (uint[])
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint[] memory buyersBalances = new uint[](length);
for (uint i = 0; i < length; i++) {
uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]);
buyersBalances[i] = buyerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user];
}
return buyersBalances;
}
| 7,683,297 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../libraries/Address.sol";
import "../libraries/Context.sol";
import "../utils/ERC165.sol";
import "../interfaces/ICloneablePaymentSplitter.sol";
// OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol)
// OpenZeppelin Contract Commit Hash: 6bd6b76d1156e20e45d1016f355d154141c7e5b9
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*
* NOTE: The following modifications have been made to OpenZeppelin's PaymentSplitter.sol contract
*
* 1. Exposed pendingPayment functions publicly to support pending payment queries.
* 2. Moved payee/shares initialization logic from constructor to initialize function to
* make this contract cloneable via EIP-1167.
* 3. Defined functions via ICloneablePaymentSplitter interface
*/
contract CloneablePaymentSplitter is Context, ERC165, ICloneablePaymentSplitter {
bool private _initialized;
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
constructor() payable {
}
/**
* @dev Initializes this instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
function initialize(address[] calldata payees, uint256[] calldata shares_) external override {
require(!_initialized, "PaymentSplitter: already initialized");
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
_initialized = true;
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() external view override returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view override returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view override returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) external view override returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view override returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view override returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) external view override returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) external virtual override {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
emit PaymentReleased(account, payment);
Address.sendValue(account, payment);
}
/**
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
* contract.
*/
function release(IERC20 token, address account) external virtual override {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20Released[token][account] += payment;
_erc20TotalReleased[token] += payment;
emit ERC20PaymentReleased(token, account, payment);
SafeERC20.safeTransfer(token, account, payment);
}
function pendingPayment(address account) external virtual view override returns (uint256) {
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
return payment;
}
function pendingPayment(IERC20 token, address account) external virtual view override returns (uint256) {
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
return payment;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(ICloneablePaymentSplitter).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../interfaces/IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./IERC165.sol";
import "../libraries/SafeERC20.sol";
interface ICloneablePaymentSplitter is IERC165 {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
function initialize(address[] calldata payees, uint256[] calldata shares_) external;
function totalShares() external view returns (uint256);
function totalReleased() external view returns (uint256);
function totalReleased(IERC20 token) external view returns (uint256);
function shares(address account) external view returns (uint256);
function released(address account) external view returns (uint256);
function released(IERC20 token, address account) external view returns (uint256);
function payee(uint256 index) external view returns (address);
function release(address payable account) external;
function release(IERC20 token, address account) external;
function pendingPayment(address account) external view returns (uint256);
function pendingPayment(IERC20 token, address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../interfaces/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 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.9;
/**
* @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);
}
|
Getter for the amount of shares held by an account./
|
function shares(address account) external view override returns (uint256) {
return _shares[account];
}
| 6,122,322 |
./full_match/1/0x4768dA3d9a5E43Fd1Af63B7C53DCc1A76Af208a1/sources/CryptoWarriors/CryptoWarriors.sol
|
_safeMint's second argument now takes in a quantity, not a tokenId.
|
function mint(uint256 amount) external payable callerIsNotContract whenNotPaused{
require(balanceOf(msg.sender) + amount <= MAX_PER_ADDRESS, "Exceed max buy per address");
require(totalSupply() + amount <= MAX_SUPPLY, "Exceed max token supply");
require(msg.value >= amount * price, "Not enough ETH");
_safeMint(msg.sender, amount);
}
| 4,884,299 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function parseAssetsForAction(
address _vaultProxy,
bytes4 _selector,
bytes calldata _encodedCallArgs
)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "../utils/actions/CurveAaveLiquidityActionsMixin.sol";
import "../utils/actions/CurveGaugeV2RewardsHandlerMixin.sol";
import "../utils/AdapterBase.sol";
/// @title CurveLiquidityAaveAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for liquidity provision in Curve's aave pool (https://www.curve.fi/aave)
/// @dev Rewards tokens are not included as spend assets or incoming assets for claimRewards()
/// or claimRewardsAndReinvest(). Rationale:
/// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need
/// to enforce policy management or emit an event
/// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked
contract CurveLiquidityAaveAdapter is
AdapterBase,
CurveGaugeV2RewardsHandlerMixin,
CurveAaveLiquidityActionsMixin
{
address private immutable AAVE_DAI_TOKEN;
address private immutable AAVE_USDC_TOKEN;
address private immutable AAVE_USDT_TOKEN;
address private immutable DAI_TOKEN;
address private immutable USDC_TOKEN;
address private immutable USDT_TOKEN;
address private immutable LIQUIDITY_GAUGE_TOKEN;
address private immutable LP_TOKEN;
constructor(
address _integrationManager,
address _liquidityGaugeToken,
address _lpToken,
address _minter,
address _pool,
address _crvToken,
address[3] memory _aaveTokens, // [aDAI, aUSDC, aUSDT]
address[3] memory _underlyingTokens // [DAI, USDC, USDT]
)
public
AdapterBase(_integrationManager)
CurveAaveLiquidityActionsMixin(_pool, _aaveTokens, _underlyingTokens)
CurveGaugeV2RewardsHandlerMixin(_minter, _crvToken)
{
AAVE_DAI_TOKEN = _aaveTokens[0];
AAVE_USDC_TOKEN = _aaveTokens[1];
AAVE_USDT_TOKEN = _aaveTokens[2];
DAI_TOKEN = _underlyingTokens[0];
USDC_TOKEN = _underlyingTokens[1];
USDT_TOKEN = _underlyingTokens[2];
LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken;
LP_TOKEN = _lpToken;
// Max approve liquidity gauge to spend LP token
ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max);
}
// EXTERNAL FUNCTIONS
/// @notice Claims rewards from the Curve liquidity gauge as well as pool-specific rewards
/// @param _vaultProxy The VaultProxy of the calling fund
function claimRewards(
address _vaultProxy,
bytes calldata,
bytes calldata
) external onlyIntegrationManager {
__curveGaugeV2ClaimAllRewards(LIQUIDITY_GAUGE_TOKEN, _vaultProxy);
}
/// @notice Lends assets for LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function lend(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256[3] memory orderedOutgoingAmounts,
uint256 minIncomingLPTokenAmount,
bool useUnderlyings
) = __decodeLendCallArgs(_actionData);
__curveAaveLend(orderedOutgoingAmounts, minIncomingLPTokenAmount, useUnderlyings);
}
/// @notice Lends assets for LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function lendAndStake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256[3] memory orderedOutgoingAmounts,
uint256 minIncomingLiquidityGaugeTokenAmount,
bool useUnderlyings
) = __decodeLendCallArgs(_actionData);
__curveAaveLend(
orderedOutgoingAmounts,
minIncomingLiquidityGaugeTokenAmount,
useUnderlyings
);
__curveGaugeV2Stake(
LIQUIDITY_GAUGE_TOKEN,
LP_TOKEN,
ERC20(LP_TOKEN).balanceOf(address(this))
);
}
/// @notice Redeems LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function redeem(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256 outgoingLPTokenAmount,
uint256[3] memory orderedMinIncomingAssetAmounts,
bool redeemSingleAsset,
bool useUnderlyings
) = __decodeRedeemCallArgs(_actionData);
__curveAaveRedeem(
outgoingLPTokenAmount,
orderedMinIncomingAssetAmounts,
redeemSingleAsset,
useUnderlyings
);
}
/// @notice Stakes LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function stake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_actionData);
__curveGaugeV2Stake(LIQUIDITY_GAUGE_TOKEN, LP_TOKEN, outgoingLPTokenAmount);
}
/// @notice Unstakes LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function unstake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_actionData);
__curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, outgoingLiquidityGaugeTokenAmount);
}
/// @notice Unstakes LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256[3] memory orderedMinIncomingAssetAmounts,
bool redeemSingleAsset,
bool useUnderlyings
) = __decodeRedeemCallArgs(_actionData);
__curveGaugeV2Unstake(LIQUIDITY_GAUGE_TOKEN, outgoingLiquidityGaugeTokenAmount);
__curveAaveRedeem(
outgoingLiquidityGaugeTokenAmount,
orderedMinIncomingAssetAmounts,
redeemSingleAsset,
useUnderlyings
);
}
/////////////////////////////
// PARSE ASSETS FOR METHOD //
/////////////////////////////
/// @notice Parses the expected assets in a particular action
/// @param _selector The function selector for the callOnIntegration
/// @param _actionData Data specific to this action
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForAction(
address,
bytes4 _selector,
bytes calldata _actionData
)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == CLAIM_REWARDS_SELECTOR) {
return __parseAssetsForClaimRewards();
} else if (_selector == LEND_SELECTOR) {
return __parseAssetsForLend(_actionData);
} else if (_selector == LEND_AND_STAKE_SELECTOR) {
return __parseAssetsForLendAndStake(_actionData);
} else if (_selector == REDEEM_SELECTOR) {
return __parseAssetsForRedeem(_actionData);
} else if (_selector == STAKE_SELECTOR) {
return __parseAssetsForStake(_actionData);
} else if (_selector == UNSTAKE_SELECTOR) {
return __parseAssetsForUnstake(_actionData);
} else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) {
return __parseAssetsForUnstakeAndRedeem(_actionData);
}
revert("parseAssetsForAction: _selector invalid");
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewards() calls.
/// No action required, all values empty.
function __parseAssetsForClaimRewards()
private
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
return (
IIntegrationManager.SpendAssetsHandleType.None,
new address[](0),
new uint256[](0),
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lend() calls
function __parseAssetsForLend(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256[3] memory orderedOutgoingAssetAmounts,
uint256 minIncomingLpTokenAmount,
bool useUnderlyings
) = __decodeLendCallArgs(_actionData);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
orderedOutgoingAssetAmounts,
useUnderlyings
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingLpTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lendAndStake() calls
function __parseAssetsForLendAndStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256[3] memory orderedOutgoingAssetAmounts,
uint256 minIncomingLiquidityGaugeTokenAmount,
bool useUnderlyings
) = __decodeLendCallArgs(_actionData);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
orderedOutgoingAssetAmounts,
useUnderlyings
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingLiquidityGaugeTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during redeem() calls
function __parseAssetsForRedeem(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingLpTokenAmount,
uint256[3] memory orderedMinIncomingAssetAmounts,
bool receiveSingleAsset,
bool useUnderlyings
) = __decodeRedeemCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLpTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
orderedMinIncomingAssetAmounts,
receiveSingleAsset,
useUnderlyings
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during stake() calls
function __parseAssetsForStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
uint256 outgoingLpTokenAmount = __decodeStakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLpTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLpTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstake() calls
function __parseAssetsForUnstake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstakeAndRedeem() calls
function __parseAssetsForUnstakeAndRedeem(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256[3] memory orderedMinIncomingAssetAmounts,
bool receiveSingleAsset,
bool useUnderlyings
) = __decodeRedeemCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
orderedMinIncomingAssetAmounts,
receiveSingleAsset,
useUnderlyings
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls
function __parseIncomingAssetsForRedemptionCalls(
uint256[3] memory _orderedMinIncomingAssetAmounts,
bool _receiveSingleAsset,
bool _useUnderlyings
)
private
view
returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_)
{
if (_receiveSingleAsset) {
incomingAssets_ = new address[](1);
minIncomingAssetAmounts_ = new uint256[](1);
for (uint256 i; i < _orderedMinIncomingAssetAmounts.length; i++) {
if (_orderedMinIncomingAssetAmounts[i] == 0) {
continue;
}
// Validate that only one min asset amount is set
for (uint256 j = i + 1; j < _orderedMinIncomingAssetAmounts.length; j++) {
require(
_orderedMinIncomingAssetAmounts[j] == 0,
"__parseIncomingAssetsForRedemptionCalls: Too many min asset amounts specified"
);
}
incomingAssets_[0] = getAssetByPoolIndex(i, _useUnderlyings);
minIncomingAssetAmounts_[0] = _orderedMinIncomingAssetAmounts[i];
break;
}
require(
incomingAssets_[0] != address(0),
"__parseIncomingAssetsForRedemptionCalls: No min asset amount"
);
} else {
incomingAssets_ = new address[](3);
minIncomingAssetAmounts_ = new uint256[](3);
for (uint256 i; i < incomingAssets_.length; i++) {
incomingAssets_[i] = getAssetByPoolIndex(i, _useUnderlyings);
minIncomingAssetAmounts_[i] = _orderedMinIncomingAssetAmounts[i];
}
}
return (incomingAssets_, minIncomingAssetAmounts_);
}
/// @dev Helper function to parse spend assets for lend() and lendAndStake() calls
function __parseSpendAssetsForLendingCalls(
uint256[3] memory _orderedOutgoingAssetAmounts,
bool _useUnderlyings
) private view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) {
uint256 spendAssetsCount;
for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) {
if (_orderedOutgoingAssetAmounts[i] > 0) {
spendAssetsCount++;
}
}
spendAssets_ = new address[](spendAssetsCount);
spendAssetAmounts_ = new uint256[](spendAssetsCount);
uint256 spendAssetsIndex;
for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) {
if (_orderedOutgoingAssetAmounts[i] > 0) {
spendAssets_[spendAssetsIndex] = getAssetByPoolIndex(i, _useUnderlyings);
spendAssetAmounts_[spendAssetsIndex] = _orderedOutgoingAssetAmounts[i];
spendAssetsIndex++;
}
}
return (spendAssets_, spendAssetAmounts_);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _actionData)
private
pure
returns (
uint256[3] memory orderedOutgoingAmounts_,
uint256 minIncomingAssetAmount_,
bool useUnderlyings_
)
{
return abi.decode(_actionData, (uint256[3], uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for redeeming.
/// If `receiveSingleAsset_` is `true`, then one (and only one) of
/// the orderedMinIncomingAmounts_ must be >0 to indicate which asset is to be received.
function __decodeRedeemCallArgs(bytes memory _actionData)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256[3] memory orderedMinIncomingAmounts_,
bool receiveSingleAsset_,
bool useUnderlyings_
)
{
return abi.decode(_actionData, (uint256, uint256[3], bool, bool));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _actionData)
private
pure
returns (uint256 outgoingLPTokenAmount_)
{
return abi.decode(_actionData, (uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _actionData)
private
pure
returns (uint256 outgoingLiquidityGaugeTokenAmount_)
{
return abi.decode(_actionData, (uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable
/// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value
function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) {
return LIQUIDITY_GAUGE_TOKEN;
}
/// @notice Gets the `LP_TOKEN` variable
/// @return lpToken_ The `LP_TOKEN` variable value
function getLpToken() external view returns (address lpToken_) {
return LP_TOKEN;
}
/// @notice Gets an asset by its pool index and whether or not to use the underlying
/// instead of the aToken
function getAssetByPoolIndex(uint256 _index, bool _useUnderlying)
public
view
returns (address asset_)
{
if (_index == 0) {
if (_useUnderlying) {
return DAI_TOKEN;
}
return AAVE_DAI_TOKEN;
} else if (_index == 1) {
if (_useUnderlying) {
return USDC_TOKEN;
}
return AAVE_USDC_TOKEN;
} else if (_index == 2) {
if (_useUnderlying) {
return USDT_TOKEN;
}
return AAVE_USDT_TOKEN;
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../utils/AssetHelpers.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _assetData
) {
_;
(, , address[] memory incomingAssets) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) {
_;
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper to decode the _assetData param passed to adapter call
function __decodeAssetData(bytes memory _assetData)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return abi.decode(_assetData, (address[], uint256[], address[]));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Rewards
bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4(
keccak256("claimRewards(address,bytes,bytes)")
);
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../../interfaces/ICurveStableSwapAave.sol";
/// @title CurveAaveLiquidityActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with the Curve Aave pool's liquidity functions
abstract contract CurveAaveLiquidityActionsMixin {
using SafeERC20 for ERC20;
address private immutable CURVE_AAVE_LIQUIDITY_POOL;
constructor(
address _pool,
address[3] memory _aaveTokensToApprove,
address[3] memory _underlyingTokensToApprove
) public {
CURVE_AAVE_LIQUIDITY_POOL = _pool;
// Pre-approve pool to use max of each aToken and underlying,
// as specified by the inheriting contract.
// Use address(0) to skip a particular ordered asset.
for (uint256 i; i < 3; i++) {
if (_aaveTokensToApprove[i] != address(0)) {
ERC20(_aaveTokensToApprove[i]).safeApprove(_pool, type(uint256).max);
}
if (_underlyingTokensToApprove[i] != address(0)) {
ERC20(_underlyingTokensToApprove[i]).safeApprove(_pool, type(uint256).max);
}
}
}
/// @dev Helper to add liquidity to the pool.
/// _orderedOutgoingAssetAmounts = [aDAI, aUSDC, aUSDT].
function __curveAaveLend(
uint256[3] memory _orderedOutgoingAssetAmounts,
uint256 _minIncomingLPTokenAmount,
bool _useUnderlyings
) internal {
ICurveStableSwapAave(CURVE_AAVE_LIQUIDITY_POOL).add_liquidity(
_orderedOutgoingAssetAmounts,
_minIncomingLPTokenAmount,
_useUnderlyings
);
}
/// @dev Helper to remove liquidity from the pool.
/// if using _redeemSingleAsset, must pre-validate that one - and only one - asset
/// has a non-zero _orderedMinIncomingAssetAmounts value.
/// _orderedOutgoingAssetAmounts = [aDAI, aUSDC, aUSDT].
function __curveAaveRedeem(
uint256 _outgoingLPTokenAmount,
uint256[3] memory _orderedMinIncomingAssetAmounts,
bool _redeemSingleAsset,
bool _useUnderlyings
) internal {
if (_redeemSingleAsset) {
// Assume that one - and only one - asset has a non-zero min incoming asset amount
for (uint256 i; i < _orderedMinIncomingAssetAmounts.length; i++) {
if (_orderedMinIncomingAssetAmounts[i] > 0) {
ICurveStableSwapAave(CURVE_AAVE_LIQUIDITY_POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
int128(i),
_orderedMinIncomingAssetAmounts[i],
_useUnderlyings
);
return;
}
}
} else {
ICurveStableSwapAave(CURVE_AAVE_LIQUIDITY_POOL).remove_liquidity(
_outgoingLPTokenAmount,
_orderedMinIncomingAssetAmounts,
_useUnderlyings
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_AAVE_LIQUIDITY_POOL` variable
/// @return pool_ The `CURVE_AAVE_LIQUIDITY_POOL` variable value
function getCurveAaveLiquidityPool() public view returns (address pool_) {
return CURVE_AAVE_LIQUIDITY_POOL;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveLiquidityGaugeV2.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title CurveGaugeV2ActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with any Curve LiquidityGaugeV2 contract
abstract contract CurveGaugeV2ActionsMixin is AssetHelpers {
uint256 private constant CURVE_GAUGE_V2_MAX_REWARDS = 8;
/// @dev Helper to claim pool-specific rewards
function __curveGaugeV2ClaimRewards(address _gauge, address _target) internal {
ICurveLiquidityGaugeV2(_gauge).claim_rewards(_target);
}
/// @dev Helper to get list of pool-specific rewards tokens
function __curveGaugeV2GetRewardsTokens(address _gauge)
internal
view
returns (address[] memory rewardsTokens_)
{
address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS);
uint256 rewardsTokensCount;
for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) {
address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i);
if (rewardToken != address(0)) {
lpRewardsTokensWithEmpties[i] = rewardToken;
rewardsTokensCount++;
} else {
break;
}
}
rewardsTokens_ = new address[](rewardsTokensCount);
for (uint256 i; i < rewardsTokensCount; i++) {
rewardsTokens_[i] = lpRewardsTokensWithEmpties[i];
}
return rewardsTokens_;
}
/// @dev Helper to stake LP tokens
function __curveGaugeV2Stake(
address _gauge,
address _lpToken,
uint256 _amount
) internal {
__approveAssetMaxAsNeeded(_lpToken, _gauge, _amount);
ICurveLiquidityGaugeV2(_gauge).deposit(_amount, address(this));
}
/// @dev Helper to unstake LP tokens
function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal {
ICurveLiquidityGaugeV2(_gauge).withdraw(_amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveMinter.sol";
import "../../../../../utils/AddressArrayLib.sol";
import "./CurveGaugeV2ActionsMixin.sol";
/// @title CurveGaugeV2RewardsHandlerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for handling claiming and reinvesting rewards for a Curve pool
/// that uses the LiquidityGaugeV2 contract
abstract contract CurveGaugeV2RewardsHandlerMixin is CurveGaugeV2ActionsMixin {
using AddressArrayLib for address[];
address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN;
address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER;
constructor(address _minter, address _crvToken) public {
CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN = _crvToken;
CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER = _minter;
}
/// @dev Helper to claim all rewards (CRV and pool-specific).
/// Requires contract to be approved to use mint_for().
function __curveGaugeV2ClaimAllRewards(address _gauge, address _target) internal {
// Claim owed $CRV
ICurveMinter(CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER).mint_for(_gauge, _target);
// Claim owed pool-specific rewards
__curveGaugeV2ClaimRewards(_gauge, _target);
}
/// @dev Helper to get all rewards tokens for staking LP tokens
function __curveGaugeV2GetRewardsTokensWithCrv(address _gauge)
internal
view
returns (address[] memory rewardsTokens_)
{
return
__curveGaugeV2GetRewardsTokens(_gauge).addUniqueItem(
CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable
/// @return crvToken_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable value
function getCurveGaugeV2RewardsHandlerCrvToken() public view returns (address crvToken_) {
return CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN;
}
/// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable
/// @return minter_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable value
function getCurveGaugeV2RewardsHandlerMinter() public view returns (address minter_) {
return CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeV2 interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityGaugeV2 {
function claim_rewards(address) external;
function deposit(uint256, address) external;
function reward_tokens(uint256) external view returns (address);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveMinter interface
/// @author Enzyme Council <[email protected]>
interface ICurveMinter {
function mint_for(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveStableSwapAave interface
/// @author Enzyme Council <[email protected]>
interface ICurveStableSwapAave {
function add_liquidity(
uint256[3] calldata,
uint256,
bool
) external returns (uint256);
function remove_liquidity(
uint256,
uint256[3] calldata,
bool
) external returns (uint256[3] memory);
function remove_liquidity_one_coin(
uint256,
int128,
uint256,
bool
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
|
Helper function to parse spend and incoming assets from encoded call args during redeem() calls
|
function __parseAssetsForRedeem(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
uint256 outgoingLpTokenAmount,
uint256[3] memory orderedMinIncomingAssetAmounts,
bool receiveSingleAsset,
bool useUnderlyings
) = __decodeRedeemCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLpTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
orderedMinIncomingAssetAmounts,
receiveSingleAsset,
useUnderlyings
);
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
| 6,927,586 |
./partial_match/3/0x4B9c336B1c60D9c0CeB14d0aadb17c4D8153aB45/sources/ApostleItemBar.sol
|
TODO:: check ONLY_AMBASSADOR
|
function isAllowed(address _token, uint256 _id)
public
view
override
returns (bool)
{
address ownership = registry.addressOf(CONTRACT_OBJECT_OWNERSHIP);
if (_token == ownership) {
address interstellarEncoder =
registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER);
uint8 objectClass =
IInterstellarEncoder(interstellarEncoder).getObjectClass(_id);
if (
objectClass == ITEM_OBJECT_CLASS ||
objectClass == DRILL_OBJECT_CLASS
) {
return true;
require(isAmbassador(_id), "Furnace: ONLY_AMBASSADOR");
return true;
return false;
}
return allowList[_token];
}
}
| 5,071,508 |
pragma solidity ^0.4.24;
/**
* @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 Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**************************************************************
* @title Scale Token Contract
* @file Scale.sol
* @author Jared Downing and Kane Thomas of the Scale Network
* @version 1.0
*
* @section DESCRIPTION
*
* This is an ERC20-based token with staking and inflationary functionality.
*
*************************************************************/
//////////////////////////////////
/// OpenZeppelin library imports
//////////////////////////////////
/**
* @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);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) 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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
* Modified to allow minting for non-owner addresses
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(address(this).balance));
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
//////////////////////////////////
/// Scale Token
//////////////////////////////////
contract Scale is MintableToken, HasNoEther, BurnableToken {
// Libraries
using SafeMath for uint;
//////////////////////
// Token Information
//////////////////////
string public constant name = "SCALE";
string public constant symbol = "SCALE";
uint8 public constant decimals = 18;
///////////////////////////////////////////////////////////
// Variables For Staking and Pooling
///////////////////////////////////////////////////////////
// -- Pool Minting Rates and Percentages -- //
// Pool for Scale distribution to rewards pool
// Set to 0 to prohibit issuing to the pool before it is assigned
address public pool = address(0);
// Pool and Owner minted tokens per second
uint public poolMintRate;
uint public ownerMintRate;
// Amount of Scale to be staked to the pool, staking, and owner, as calculated through their percentages
uint public poolMintAmount;
uint public stakingMintAmount;
uint public ownerMintAmount;
// Scale distribution percentages
uint public poolPercentage = 70;
uint public ownerPercentage = 5;
uint public stakingPercentage = 25;
// Last time minted for owner and pool
uint public ownerTimeLastMinted;
uint public poolTimeLastMinted;
// -- Staking -- //
// Minted tokens per second
uint public stakingMintRate;
// Total Scale currently staked
uint public totalScaleStaked;
// Mapping of the timestamp => totalStaking that is created each time an address stakes or unstakes
mapping (uint => uint) totalStakingHistory;
// Variable for staking accuracy. Set to 86400 for seconds in a day so that staking gains are based on the day an account begins staking.
uint timingVariable = 86400;
// Address staking information
struct AddressStakeData {
uint stakeBalance;
uint initialStakeTime;
uint unstakeTime;
mapping (uint => uint) stakePerDay;
}
// Track all tokens staked
mapping (address => AddressStakeData) public stakeBalances;
// -- Inflation -- //
// Inflation rate begins at 100% per year and decreases by 30% per year until it reaches 10% where it decreases by 0.5% per year
uint256 inflationRate = 1000;
// Used to manage when to inflate. Allowed to inflate once per year until the rate reaches 1%.
uint256 public lastInflationUpdate;
// -- Events -- //
// Fired when tokens are staked
event Stake(address indexed staker, uint256 value);
// Fired when tokens are unstaked
event Unstake(address indexed unstaker, uint256 stakedAmount);
// Fired when a user claims their stake
event ClaimStake(address indexed claimer, uint256 stakedAmount, uint256 stakingGains);
//////////////////////////////////////////////////
/// Scale Token Functionality
//////////////////////////////////////////////////
/// @dev Scale token constructor
constructor() public {
// Assign owner
owner = msg.sender;
// Assign initial owner supply
uint _initOwnerSupply = 10000000 ether;
// Mint given to owner only one-time
bool _success = mint(msg.sender, _initOwnerSupply);
// Require minting success
require(_success);
// Set pool and owner last minted to ensure extra coins are not minted by either
ownerTimeLastMinted = now;
poolTimeLastMinted = now;
// Set minting amount for pool, staking, and owner over the course of 1 year
poolMintAmount = _initOwnerSupply.mul(poolPercentage).div(100);
ownerMintAmount = _initOwnerSupply.mul(ownerPercentage).div(100);
stakingMintAmount = _initOwnerSupply.mul(stakingPercentage).div(100);
// One year in seconds
uint _oneYearInSeconds = 31536000 ether;
// Set the rate of coins minted per second for the pool, owner, and global staking
poolMintRate = calculateFraction(poolMintAmount, _oneYearInSeconds, decimals);
ownerMintRate = calculateFraction(ownerMintAmount, _oneYearInSeconds, decimals);
stakingMintRate = calculateFraction(stakingMintAmount, _oneYearInSeconds, decimals);
// Set the last time inflation was updated to now so that the next time it can be updated is 1 year from now
lastInflationUpdate = now;
}
/////////////
// Inflation
/////////////
/// @dev the inflation rate begins at 100% and decreases by 30% every year until it reaches 10%
/// at 10% the rate begins to decrease by 0.5% until it reaches 1%
function adjustInflationRate() private {
// Make sure adjustInflationRate cannot be called for at least another year
lastInflationUpdate = now;
// Decrease inflation rate by 30% each year
if (inflationRate > 100) {
inflationRate = inflationRate.sub(300);
}
// Inflation rate reaches 10%. Decrease inflation rate by 0.5% from here on out until it reaches 1%.
else if (inflationRate > 10) {
inflationRate = inflationRate.sub(5);
}
adjustMintRates();
}
/// @dev adjusts the mint rate when the yearly inflation update is called
function adjustMintRates() internal {
// Calculate new mint amount of Scale that should be created per year.
poolMintAmount = totalSupply.mul(inflationRate).div(1000).mul(poolPercentage).div(100);
ownerMintAmount = totalSupply.mul(inflationRate).div(1000).mul(ownerPercentage).div(100);
stakingMintAmount = totalSupply.mul(inflationRate).div(1000).mul(stakingPercentage).div(100);
// Adjust Scale created per-second for each rate
poolMintRate = calculateFraction(poolMintAmount, 31536000 ether, decimals);
ownerMintRate = calculateFraction(ownerMintAmount, 31536000 ether, decimals);
stakingMintRate = calculateFraction(stakingMintAmount, 31536000 ether, decimals);
}
/// @dev anyone can call this function to update the inflation rate yearly
function updateInflationRate() public {
// Require 1 year to have passed for every inflation adjustment
require(now.sub(lastInflationUpdate) >= 31536000);
adjustInflationRate();
}
/////////////
// Staking
/////////////
/// @dev staking function which allows users to stake an amount of tokens to gain interest for up to 1 year
function stake(uint _stakeAmount) external {
// Require that tokens are staked successfully
require(stakeScale(msg.sender, _stakeAmount));
}
/// @dev staking function which allows users to stake an amount of tokens for another user
function stakeFor(address _user, uint _amount) external {
// Stake for the user
require(stakeScale(_user, _amount));
}
/// @dev Transfer tokens from the contract to the user when unstaking
/// @param _value uint256 the amount of tokens to be transferred
function transferFromContract(uint _value) internal {
// Sanity check to make sure we are not transferring more than the contract has
require(_value <= balances[address(this)]);
// Add to the msg.sender balance
balances[msg.sender] = balances[msg.sender].add(_value);
// Subtract from the contract's balance
balances[address(this)] = balances[address(this)].sub(_value);
// Fire an event for transfer
emit Transfer(address(this), msg.sender, _value);
}
/// @dev stake function reduces the user's total available balance and adds it to their staking balance
/// @param _value how many tokens a user wants to stake
function stakeScale(address _user, uint256 _value) private returns (bool success) {
// You can only stake / stakeFor as many tokens as you have
require(_value <= balances[msg.sender]);
// Require the user is not in power down period
require(stakeBalances[_user].unstakeTime == 0);
// Transfer tokens to contract address
transfer(address(this), _value);
// Now as a day
uint _nowAsDay = now.div(timingVariable);
// Adjust the new staking balance
uint _newStakeBalance = stakeBalances[_user].stakeBalance.add(_value);
// If this is the initial stake time, save
if (stakeBalances[_user].stakeBalance == 0) {
// Save the time that the stake started
stakeBalances[_user].initialStakeTime = _nowAsDay;
}
// Add stake amount to staked balance
stakeBalances[_user].stakeBalance = _newStakeBalance;
// Assign the total amount staked at this day
stakeBalances[_user].stakePerDay[_nowAsDay] = _newStakeBalance;
// Increment the total staked tokens
totalScaleStaked = totalScaleStaked.add(_value);
// Set the new staking history
setTotalStakingHistory();
// Fire an event for newly staked tokens
emit Stake(_user, _value);
return true;
}
/// @dev deposit a user's initial stake plus earnings if the user unstaked at least 14 days ago
function claimStake() external returns (bool) {
// Require that at least 14 days have passed (days)
require(now.div(timingVariable).sub(stakeBalances[msg.sender].unstakeTime) >= 14);
// Get the user's stake balance
uint _userStakeBalance = stakeBalances[msg.sender].stakeBalance;
// Calculate tokens to mint using unstakeTime, rewards are not received during power-down period
uint _tokensToMint = calculateStakeGains(stakeBalances[msg.sender].unstakeTime);
// Clear out stored data from mapping
stakeBalances[msg.sender].stakeBalance = 0;
stakeBalances[msg.sender].initialStakeTime = 0;
stakeBalances[msg.sender].unstakeTime = 0;
// Return the stake balance to the staker
transferFromContract(_userStakeBalance);
// Mint the new tokens to the sender
mint(msg.sender, _tokensToMint);
// Scale unstaked event
emit ClaimStake(msg.sender, _userStakeBalance, _tokensToMint);
return true;
}
/// @dev allows users to start the reclaim process for staked tokens and stake rewards
/// @return bool on success
function initUnstake() external returns (bool) {
// Require that the user has not already started the unstaked process
require(stakeBalances[msg.sender].unstakeTime == 0);
// Require that there was some amount staked
require(stakeBalances[msg.sender].stakeBalance > 0);
// Log time that user started unstaking
stakeBalances[msg.sender].unstakeTime = now.div(timingVariable);
// Subtract stake balance from totalScaleStaked
totalScaleStaked = totalScaleStaked.sub(stakeBalances[msg.sender].stakeBalance);
// Set this every time someone adjusts the totalScaleStaked amount
setTotalStakingHistory();
// Scale unstaked event
emit Unstake(msg.sender, stakeBalances[msg.sender].stakeBalance);
return true;
}
/// @dev function to let the user know how much time they have until they can claim their tokens from unstaking
/// @param _user to check the time until claimable of
/// @return uint time in seconds until they may claim
function timeUntilClaimAvaliable(address _user) view external returns (uint) {
return stakeBalances[_user].unstakeTime.add(14).mul(86400);
}
/// @dev function to check the staking balance of a user
/// @param _user to check the balance of
/// @return uint of the stake balance
function stakeBalanceOf(address _user) view external returns (uint) {
return stakeBalances[_user].stakeBalance;
}
/// @dev returns how much Scale a user has earned so far
/// @param _now is passed in to allow for a gas-free analysis
/// @return staking gains based on the amount of time passed since staking began
function getStakingGains(uint _now) view public returns (uint) {
if (stakeBalances[msg.sender].stakeBalance == 0) {
return 0;
}
return calculateStakeGains(_now.div(timingVariable));
}
/// @dev Calculates staking gains
/// @param _unstakeTime when the user stopped staking.
/// @return uint for total coins to be minted
function calculateStakeGains(uint _unstakeTime) view private returns (uint mintTotal) {
uint _initialStakeTimeInVariable = stakeBalances[msg.sender].initialStakeTime; // When the user started staking as a unique day in unix time
uint _timePassedSinceStakeInVariable = _unstakeTime.sub(_initialStakeTimeInVariable); // How much time has passed, in days, since the user started staking.
uint _stakePercentages = 0; // Keeps an additive track of the user's staking percentages over time
uint _tokensToMint = 0; // How many new Scale tokens to create
uint _lastDayStakeWasUpdated; // Last day the totalScaleStaked was updated
uint _lastStakeDay; // Last day that the user staked
// If user staked and init unstaked on the same day, gains are 0
if (_timePassedSinceStakeInVariable == 0) {
return 0;
}
// If user has been staking longer than 365 days, staked days after 365 days do not earn interest
else if (_timePassedSinceStakeInVariable >= 365) {
_unstakeTime = _initialStakeTimeInVariable.add(365);
_timePassedSinceStakeInVariable = 365;
}
// Average this msg.sender's relative percentage ownership of totalScaleStaked throughout each day since they started staking
for (uint i = _initialStakeTimeInVariable; i < _unstakeTime; i++) {
// Total amount user has staked on i day
uint _stakeForDay = stakeBalances[msg.sender].stakePerDay[i];
// If this was a day that the user staked or added stake
if (_stakeForDay != 0) {
// If the day exists add it to the percentages
if (totalStakingHistory[i] != 0) {
// If the day does exist add it to the number to be later averaged as a total average percentage of total staking
_stakePercentages = _stakePercentages.add(calculateFraction(_stakeForDay, totalStakingHistory[i], decimals));
// Set the last day someone staked
_lastDayStakeWasUpdated = totalStakingHistory[i];
}
else {
// Use the last day found in the totalStakingHistory mapping
_stakePercentages = _stakePercentages.add(calculateFraction(_stakeForDay, _lastDayStakeWasUpdated, decimals));
}
_lastStakeDay = _stakeForDay;
}
else {
// If the day exists add it to the percentages
if (totalStakingHistory[i] != 0) {
// If the day does exist add it to the number to be later averaged as a total average percentage of total staking
_stakePercentages = _stakePercentages.add(calculateFraction(_lastStakeDay, totalStakingHistory[i], decimals));
// Set the last day someone staked
_lastDayStakeWasUpdated = totalStakingHistory[i];
}
else {
// Use the last day found in the totalStakingHistory mapping
_stakePercentages = _stakePercentages.add(calculateFraction(_lastStakeDay, _lastDayStakeWasUpdated, decimals));
}
}
}
// Get the account's average percentage staked of the total stake over the course of all days they have been staking
uint _stakePercentageAverage = calculateFraction(_stakePercentages, _timePassedSinceStakeInVariable, 0);
// Calculate this account's mint rate per second while staking
uint _finalMintRate = stakingMintRate.mul(_stakePercentageAverage);
// Account for 18 decimals when calculating the amount of tokens to mint
_finalMintRate = _finalMintRate.div(1 ether);
// Calculate total tokens to be minted. Multiply by timingVariable to convert back to seconds.
_tokensToMint = calculateMintTotal(_timePassedSinceStakeInVariable.mul(timingVariable), _finalMintRate);
return _tokensToMint;
}
/// @dev set the new totalStakingHistory mapping to the current timestamp and totalScaleStaked
function setTotalStakingHistory() private {
// Get now in terms of the variable staking accuracy (days in Scale's case)
uint _nowAsTimingVariable = now.div(timingVariable);
// Set the totalStakingHistory as a timestamp of the totalScaleStaked today
totalStakingHistory[_nowAsTimingVariable] = totalScaleStaked;
}
/////////////
// Scale Owner Claiming
/////////////
/// @dev allows contract owner to claim their allocated mint
function ownerClaim() external onlyOwner {
require(now > ownerTimeLastMinted);
uint _timePassedSinceLastMint; // The amount of time passed since the owner claimed in seconds
uint _tokenMintCount; // The amount of new tokens to mint
bool _mintingSuccess; // The success of minting the new Scale tokens
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(ownerTimeLastMinted);
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, ownerMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(msg.sender, _tokenMintCount);
require(_mintingSuccess);
// New minting was a success. Set last time minted to current block.timestamp (now)
ownerTimeLastMinted = now;
}
////////////////////////////////
// Scale Pool Distribution
////////////////////////////////
// @dev anyone can call this function that mints Scale to the pool dedicated to Scale distribution to rewards pool
function poolIssue() public {
// Do not allow tokens to be minted to the pool until the pool is set
require(pool != address(0));
// Make sure time has passed since last minted to pool
require(now > poolTimeLastMinted);
require(pool != address(0));
uint _timePassedSinceLastMint; // The amount of time passed since the pool claimed in seconds
uint _tokenMintCount; // The amount of new tokens to mint
bool _mintingSuccess; // The success of minting the new Scale tokens
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(poolTimeLastMinted);
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, poolMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(pool, _tokenMintCount);
require(_mintingSuccess);
// New minting was a success! Set last time minted to current block.timestamp (now)
poolTimeLastMinted = now;
}
/// @dev sets the address for the rewards pool
/// @param _newAddress pool Address
function setPool(address _newAddress) public onlyOwner {
pool = _newAddress;
}
////////////////////////////////
// Helper Functions
////////////////////////////////
/// @dev calculateFraction allows us to better handle the Solidity ugliness of not having decimals as a native type
/// @param _numerator is the top part of the fraction we are calculating
/// @param _denominator is the bottom part of the fraction we are calculating
/// @param _precision tells the function how many significant digits to calculate out to
/// @return quotient returns the result of our fraction calculation
function calculateFraction(uint _numerator, uint _denominator, uint _precision) pure private returns(uint quotient) {
// Take passed value and expand it to the required precision
_numerator = _numerator.mul(10 ** (_precision + 1));
// Handle last-digit rounding
uint _quotient = ((_numerator.div(_denominator)) + 5) / 10;
return (_quotient);
}
/// @dev Determines the amount of Scale to create based on the number of seconds that have passed
/// @param _timeInSeconds is the time passed in seconds to mint for
/// @return uint with the calculated number of new tokens to mint
function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount) {
// Calculates the amount of tokens to mint based upon the number of seconds passed
return(_timeInSeconds.mul(_mintRate));
}
}
|
Transfer tokens from the contract to the user when unstaking _value uint256 the amount of tokens to be transferred Sanity check to make sure we are not transferring more than the contract has Add to the msg.sender balance Subtract from the contract's balance Fire an event for transfer
|
function transferFromContract(uint _value) internal {
require(_value <= balances[address(this)]);
balances[msg.sender] = balances[msg.sender].add(_value);
balances[address(this)] = balances[address(this)].sub(_value);
emit Transfer(address(this), msg.sender, _value);
}
| 12,235,971 |
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
|
Reads the uint56 at `mPtr` in memory.
|
function readUint56(
MemoryPointer mPtr
) internal pure returns (uint56 value) {
assembly ("memory-safe") {
value := mload(mPtr)
}
}
| 8,452,079 |
//Address: 0x37592e023cf717da41a15effba4cf7b5f3fed85c
//Contract name: LightFundsRegistry
//Balance: 0.19 Ether
//Verification Date: 12/17/2017
//Transacion Count: 0
// CODE STARTS HERE
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
}
contract ArgumentsChecker {
/// @dev check which prevents short address attack
modifier payloadSizeIs(uint size) {
require(msg.data.length == size + 4 /* function selector */);
_;
}
/// @dev check that address is valid
modifier validAddress(address addr) {
require(addr != address(0));
_;
}
}
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;
}
}
contract LightFundsRegistry is ArgumentsChecker, Ownable, ReentrancyGuard {
using SafeMath for uint256;
enum State {
// gathering funds
GATHERING,
// returning funds to investors
REFUNDING,
// funds sent to owners
SUCCEEDED
}
event StateChanged(State _state);
event Invested(address indexed investor, uint256 amount);
event EtherSent(address indexed to, uint value);
event RefundSent(address indexed to, uint value);
modifier requiresState(State _state) {
require(m_state == _state);
_;
}
// PUBLIC interface
function LightFundsRegistry(address owner80, address owner20)
public
validAddress(owner80)
validAddress(owner20)
{
m_owner80 = owner80;
m_owner20 = owner20;
}
/// @dev performs only allowed state transitions
function changeState(State _newState)
external
onlyOwner
{
assert(m_state != _newState);
if (State.GATHERING == m_state) { assert(State.REFUNDING == _newState || State.SUCCEEDED == _newState); }
else assert(false);
m_state = _newState;
StateChanged(m_state);
if (State.SUCCEEDED == _newState) {
uint _80percent = this.balance.mul(80).div(100);
m_owner80.transfer(_80percent);
EtherSent(m_owner80, _80percent);
uint _20percent = this.balance;
m_owner20.transfer(_20percent);
EtherSent(m_owner20, _20percent);
}
}
/// @dev records an investment
function invested(address _investor)
external
payable
onlyOwner
requiresState(State.GATHERING)
{
uint256 amount = msg.value;
require(0 != amount);
// register investor
if (0 == m_weiBalances[_investor])
m_investors.push(_investor);
// register payment
totalInvested = totalInvested.add(amount);
m_weiBalances[_investor] = m_weiBalances[_investor].add(amount);
Invested(_investor, amount);
}
/// @notice withdraw accumulated balance, called by payee in case crowdsale has failed
function withdrawPayments(address payee)
external
nonReentrant
onlyOwner
requiresState(State.REFUNDING)
{
uint256 payment = m_weiBalances[payee];
require(payment != 0);
require(this.balance >= payment);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
payee.transfer(payment);
RefundSent(payee, payment);
}
function getInvestorsCount() external view returns (uint) { return m_investors.length; }
// FIELDS
/// @notice total amount of investments in wei
uint256 public totalInvested;
/// @notice state of the registry
State public m_state = State.GATHERING;
/// @dev balances of investors in wei
mapping(address => uint256) public m_weiBalances;
/// @dev list of unique investors
address[] public m_investors;
address public m_owner80;
address public m_owner20;
}
|
withdraw accumulated balance, called by payee in case crowdsale has failed
|
function withdrawPayments(address payee)
external
nonReentrant
onlyOwner
requiresState(State.REFUNDING)
{
uint256 payment = m_weiBalances[payee];
require(payment != 0);
require(this.balance >= payment);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
payee.transfer(payment);
RefundSent(payee, payment);
}
address public m_owner80;
address public m_owner20;
| 12,712,087 |
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/LiveMintTokyo.sol
|
Returns The City Struct At Index Of `CityIndex`/
|
function readCitizenCity(uint CityIndex) public view returns(City memory) { return Cities[CityIndex]; }
| 8,470,987 |
./full_match/1/0xFfc4A01F929Fac3dA11D371c5F949b41bd32891A/sources/browser/MrBull.sol
|
bear amount from burn recipient receives the burnDivisor - 1% bear tokens sender loses the 1% of the BULL 1% sender transfers 99% of the BULL
|
function transferFrom(address sender, address recipient, uint256 amount) public checkRunning virtual override returns (bool) {
uint256 bearAmount = amount.div(burnDivisor);
uint256 onePct = amount.div(100);
bear.mint(sender, bearAmount > onePct ? bearAmount.sub(onePct) : bearAmount);
_burn(sender, bearAmount);
_mint(devaddr, amount.div(100));
return super.transferFrom(sender, recipient, amount.sub(bearAmount));
}
| 4,826,954 |
./full_match/5/0xd24e6Ff54E08Ac3Bb2A3765b67e07F1670b46Dfa/sources/contracts/ERC20Upgradeable.sol
|
Returns true if the denylistee is denylisted, and false otherwise./
|
function isDenylisted(address denylistee)
public
view
virtual
returns (bool)
{
return _isBalanceDenylisted(_balances[denylistee]);
}
| 7,057,291 |
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This 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 TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // 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` in 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 in 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 in 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;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract DinsteinCoin is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function DinsteinCoin(
uint256 initialSupply,
uint256 tokenSellPrice,
uint256 tokenBuyPrice,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {
sellPrice = tokenSellPrice;
buyPrice = tokenBuyPrice;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
/// @notice Retrieve `amount` ether to owner
function retrieve(uint256 amount) onlyOwner public {
require(this.balance >= amount); // checks if the contract has enough ether to retrieve
owner.transfer(amount); // sends ether to the owner.
}
/// @notice Retrieve all ether to owner
function retrieveAll() onlyOwner public {
require(this.balance > 0);
owner.transfer(this.balance); // sends ether to the owner.
}
}
|
Retrieve `amount` ether to owner
|
function retrieve(uint256 amount) onlyOwner public {
}
| 5,962,717 |
./partial_match/1/0xDf100fa9A871669F1c99649fE7852Ff45228a83B/sources/Star3Dlong.sol
|
set up our tx event data fetch player ID manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
|
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
Star3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
| 3,587,713 |
./full_match/4/0x33CC0d896932F63eB11C4bEBB6D76278c4AE78c8/sources/contracts/NekoDaruma.sol
|
Function to withdraw funds from the contract
|
function withdrawBalance() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
| 652,274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.