file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/80001/0x12e49Ba4c1015Fb655d88ECb965dbf22F1ae34C2/sources/contracts/GameMarkeplace.sol
|
Get a pool by ID. _categoryId The ID of the category/
|
function getPool(uint256 _categoryId) public view returns (uint256 id, uint256 categoryId, bool isActive, Item[] memory availableItems, Item[] memory rentedItems) {
Pool storage pool = pools[_categoryId];
return (pool.id, pool.categoryId, pool.isActive, pool.availableItems, pool.rentedItems);
}
| 5,687,228 |
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title BetCycleBasic
* @dev Basic bet cycle contract.
*/
contract BetCycleBasic is Ownable {
using SafeMath for uint256;
/**
* @dev Event triggered on successful betting.
*
* @param gambler Gambler address.
* @param prediction Prediction.
* @param bet Amount of money bet.
*/
event Bet(
address indexed gambler,
bytes32 indexed prediction,
uint256 bet
);
/**
* @dev Event triggered when a bet is cancelled.
*
* @param gambler Gambler address.
* @param prediction Prediction.
* @param bet Amount of money bet.
*/
event BetCancelled(
address indexed gambler,
bytes32 indexed prediction,
uint256 bet
);
/**
* @dev Event triggered when the outcome of the bet has been set.
*
* @param outcome Outcome.
* @param payout Prize per wei.
*/
event Outcome(
bytes32 indexed outcome,
uint256 payout
);
/**
* @dev Event triggered when a gambler requested a refund.
*
* @param gambler Gambler address.
* @param amount Amount returned.
*/
event Refund(
address indexed gambler,
uint256 amount
);
/**
* @dev Event triggered when a prize has been claimed.
*
* @param winner Winner address.
* @param prize Prized amount.
*/
event ClaimedPrize(
address indexed winner,
uint256 prize
);
/////////////
// Commission
/**
* @dev Prize base percentage.
*/
uint8 public prizeBase;
//////////////////
// Betting periods
/**
* @dev Betting cycle start block.
*/
uint256 public bettingBlock;
/**
* @dev Outcome publishing cycle start block.
*/
uint256 public publishingBlock;
/**
* @dev Claiming cycle start block.
*/
uint256 public claimingBlock;
/**
* @dev Ending betting start block.
*/
uint256 public endingBlock;
/**
* @dev Outcome of the bet.
*/
bytes32 public outcome;
/**
* @dev Prize per wei.
*/
uint256 public payout;
/**
* @dev When is on the betting period (∞, bettingBlock].
*/
modifier isBettingPeriod() {
require(
block.number <= bettingBlock,
"The betting period has already ended."
);
_;
}
/**
* @dev When is on the publishing period [publishingBlock, claimingBlock).
*/
modifier isPublishingPeriod() {
require(
publishingBlock <= block.number && block.number < claimingBlock,
"It is not the publishing period."
);
_;
}
/**
* @dev When is on the claiming period [claimingBlock, endingBlock).
*/
modifier isClaimingPeriod() {
require(
claimingBlock <= block.number && block.number < endingBlock,
"It is not the claiming period."
);
_;
}
/**
* @dev When the betting cycle has ended [endingBlock, ∞).
*/
modifier hasEnded() {
require(
endingBlock <= block.number,
"The bet has not ended."
);
_;
}
/**
* @dev When has outcome.
*/
modifier hasOutcome() {
require(
outcome != 0x0,
"There is no outcome yet."
);
_;
}
/**
* @dev When has not outcome.
*/
modifier hasNoOutcome() {
require(
outcome == 0x0,
"There is already an outcome."
);
_;
}
/**
* @dev When the prize or the refund has not been claimed.
*/
modifier hasNotClaimed() {
require(
!_claimed[msg.sender],
"The ether was already claimed."
);
_;
}
/**
* @dev When the gambler has won.
*/
modifier hasWon() {
require(
_predictions[msg.sender] == outcome,
"The sender did not win the bet."
);
_;
}
//////////////////////
// Betting information
/**
* @dev Bets by address.
*/
mapping(address => uint256) _bets;
/**
* @dev Predictions by address.
*/
mapping(address => bytes32) _predictions;
/**
* @dev Prediction count by predictions.
*/
mapping(bytes32 => uint256) _count;
/**
* @dev Whether the address claimed the prize or not.
*/
mapping(address => bool) _claimed;
/**
* @dev When the gambler has not bet.
*/
modifier hasNotBet() {
require(
_bets[msg.sender] == 0,
"The sender has already bet."
);
require(
_predictions[msg.sender] == 0x0,
"The sender has already a valid prediction."
);
_;
}
/**
* @dev When the gambler has bet.
*/
modifier hasBet() {
require(
_bets[msg.sender] > 0,
"The sender has not bet yet."
);
require(
_predictions[msg.sender] != 0x0,
"The sender does not have a valid prediction."
);
_;
}
/**
* @dev This contract does not accept payments via send or transfer.
*/
function () public {}
/**
* @dev Given offsets, starts a betting cycle.
*
* @param commission Commission of the contract.
* @param bettingOffset Betting offset from the creation block.
* @param publishingOffset Result publishing offset. Must be greater than
* bettingOffset.
* @param claimingOffset Claiming offset from the creation block. Must be
* greater than the publishingOffset.
* @param endingOffset Bet cycle ending block offset from the creation block.
* Must be greater than the claimingOffset.
*/
constructor(
uint8 commission,
uint256 bettingOffset,
uint256 publishingOffset,
uint256 claimingOffset,
uint256 endingOffset
) public {
require(
commission <= 100,
"Commission cannot exceed 100%."
);
require(
bettingOffset < publishingOffset,
"The publishing offset must be greater than the betting offset."
);
require(
publishingOffset < claimingOffset,
"The claiming offset must be greater than the publishing offset."
);
require(
claimingOffset < endingOffset,
"The ending offset must be greater than the claiming offset."
);
prizeBase = 100 - commission;
bettingBlock = block.number.add(bettingOffset);
publishingBlock = block.number.add(publishingOffset);
claimingBlock = block.number.add(claimingOffset);
endingBlock = block.number.add(endingOffset);
outcome = 0x0;
payout = 0;
}
//////////////////////////////
// Information views functions
/**
* @dev Gets the prediction of a gambler.
*
* @param gambler Address of the gambler.
*
* @return Prediction of the gambler.
*/
function getPrediction(address gambler) public view returns (bytes32) {
return _predictions[gambler];
}
/**
* @dev Gets the amount bet by a gambler.
*
* @param gambler Address of the gambler
*
* @return Amount of Ether bet.
*/
function getBet(address gambler) public view returns (uint256) {
return _bets[gambler];
}
/**
* @dev Gets amount of support for a bet.
*
* @param prediction Prediction.
*
* @return Prediction support.
*/
function getSupport(bytes32 prediction) public view returns (uint256) {
return _count[prediction];
}
///////////////////////////
// Betting period functions
/**
* @dev Bets an amount of Ether on a prediction.
*
* @param prediction Prediction.
*
* @return Whether the bet was set or not.
*/
function bet(bytes32 prediction)
public hasNotBet isBettingPeriod payable returns (bool) {
require(
prediction != 0x0,
"The prediction must not be empty."
);
require(
msg.value > 0,
"The ether sent must be greater than zero."
);
_bets[msg.sender] = msg.value;
_predictions[msg.sender] = prediction;
_count[prediction] = _count[prediction].add(msg.value);
emit Bet(msg.sender, prediction, msg.value);
return true;
}
/**
* @dev Cancels a bet returning the bet Ether to the sender.
*
* @return Whether the bet was cancelled or not.
*/
function cancelBet()
public hasBet isBettingPeriod returns (bool) {
bytes32 prediction = getPrediction(msg.sender);
uint256 amount = getBet(msg.sender);
delete _bets[msg.sender];
delete _predictions[msg.sender];
uint256 count = _count[prediction].sub(amount);
if ( count == 0 ) {
delete _count[prediction];
} else {
_count[prediction] = count;
}
msg.sender.transfer(amount);
emit BetCancelled(msg.sender, prediction, amount);
return true;
}
//////////////////////////////
// Publishing period functions
/**
* @dev Sets outcome of the bet.
*
* @param _outcome Outcome of the bet.
*
* @return Whether the outcome has been set or not.
*/
function setOutcome(bytes32 _outcome)
public onlyOwner hasNoOutcome isPublishingPeriod returns (bool) {
uint256 winnerPool = _count[_outcome];
require(
_outcome != 0x0,
"Outcome cannot be empty."
);
uint256 totalPool = address(this).balance;
if ( winnerPool == totalPool ) {
return true;
} else if ( 0 < winnerPool && winnerPool < totalPool ) {
payout = totalPool.mul(prizeBase).div(winnerPool);
}
outcome = _outcome;
emit Outcome(outcome, payout);
return true;
}
////////////////////////////
// Claiming period functions
/**
* @dev Refunds the ether when the outcome is not set on time.
*
* @return Whether the ether was returned or not.
*/
function refund() public hasBet hasNoOutcome hasNotClaimed returns (bool) {
require(
claimingBlock <= block.number,
"No refunds yet available."
);
uint256 amount = getBet(msg.sender);
_claimed[msg.sender] = true;
msg.sender.transfer(amount);
emit Refund(msg.sender, amount);
return true;
}
/**
* @dev Sends the prize to the winner.
*
* @return Whether the prize was transferred or not.
*/
function claim()
public hasBet hasOutcome isClaimingPeriod hasNotClaimed hasWon
returns (bool) {
uint256 amount = _bets[msg.sender];
uint256 prize = amount.mul(payout).div(100);
_claimed[msg.sender] = true;
msg.sender.transfer(prize);
emit ClaimedPrize(msg.sender, prize);
return true;
}
//////////////////////////
// Ending period functions
/**
* @dev Ends bet cycle by sending the balance of the contract to the
* destination address.
*
* @param destination Destination address.
*
* @return Whether the balance could be sent or not.
*/
function endBetCycle(address destination)
public onlyOwner hasOutcome hasEnded returns (bool) {
require(
destination != address(0x0),
"Destination address cannot be zero address"
);
destination.transfer(address(this).balance);
return true;
}
}
|
Ends bet cycle by sending the balance of the contract to the destination address. destination Destination address. return Whether the balance could be sent or not./
|
function endBetCycle(address destination)
public onlyOwner hasOutcome hasEnded returns (bool) {
require(
destination != address(0x0),
"Destination address cannot be zero address"
);
destination.transfer(address(this).balance);
return true;
}
| 14,083,259 |
./full_match/80001/0xd0f330338c533a0394d1533E47a8a4425E0Fd076/sources/contracts/Staking.sol
|
Header: Calculate staking tokens given for derivative tokens [var] _amount: Amount of derivative tokens [return] outputTokens: Amount of equivalent staking tokens note: Used by _unstake and getUnstakeQuote/
|
function _GetUnstakeQuote(uint _amount) internal view returns(uint outputTokens){
require(_amount > 0, "Amount must be greater than zero");
require(totalPool > 0, "totalPool is zero");
require(derivativeTokenGiven > 0, "Given derivativeToken is zero");
uint owedRewards = totalPool * ((scaleFactor * _amount) / derivativeTokenGiven);
outputTokens = owedRewards / scaleFactor;
return outputTokens;
}
| 9,496,563 |
./full_match/1/0x66938285B15da67A93D80D08f8f2DA665449F08d/sources/contracts/AXLPresale.sol
|
On presale failure Percentile withdrawls allows fee on transfer or rebasing tokens to still work Refund return;
|
function userWithdrawBaseTokens () public nonReentrant {
BuyerInfo storage buyer = buyers[msg.sender];
uint256 remainingBaseBalance = address(this).balance;
require(remainingBaseBalance >= buyer.base, "Nothing to withdraw.");
status.base_withdraw = status.base_withdraw.add(buyer.base);
address payable reciver = payable(msg.sender);
reciver.transfer(buyer.base);
if(msg.sender == owner) {
ownerWithdrawTokens();
}
buyer.base = 0;
buyer.sale = 0;
emit UserWithdrawSuccess(buyer.base);
| 4,929,527 |
pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract Project is Ownable {
using SafeMath for uint256;
enum State{
Ongoing,
Expired,
Completed
}
// State Variables
uint public goal; // amount in ether
string public title;
uint public deadline;
string public description;
State public state = State.Ongoing;
mapping (address=>uint) contributors; // contributors
constructor(uint _goal, string memory _title, string memory _description, address _creator, uint _deadline) {
goal = _goal;
title = _title;
description = _description;
deadline = _deadline;
transferOwnership(_creator);
}
modifier inState(State _state) {
require(state == _state);
_;
}
function contribute() external inState(State.Ongoing) payable {
require(msg.sender != owner());
contributors[msg.sender] = contributors[msg.sender].add(msg.value);
// emit FundingRecieved(msg.sender, msg.value, balance);
isComplete();
}
function isComplete() public {
uint balance = address(this).balance;
if (balance >= goal){
state = State.Completed;
// emit ProjectCompleted(msg.sender, balance, goal);
payCreator();
}
else if(block.timestamp > deadline){
state = State.Expired;
}
}
function payCreator() internal inState(State.Completed) returns(bool) {
address payable creator = payable(owner());
uint balance = address(this).balance;
// Maybe the balance exceeded the goal, so we need to update the goal.
goal = balance;
if (creator.send(balance)){
// emit CreatorPaid(creator, balance);
return true;
}
return false;
}
function balanceOf()public view returns(uint){
return address(this).balance;
}
function fetchContributors(address _contributor) public view returns(uint){
return contributors[_contributor];
}
function refund() public inState(State.Expired) {
require(contributors[msg.sender] > 0);
uint amountToRefund = contributors[msg.sender];
contributors[msg.sender] = 0;
if(payable(msg.sender).send(amountToRefund)){
// emit FundingRefunded(msg.sender, amountToRefund, address(this).balance);
}else{
contributors[msg.sender] = amountToRefund;
}
}
function expireAndRefund() public inState(State.Ongoing) {
state = State.Expired;
refund();
}
}
|
Maybe the balance exceeded the goal, so we need to update the goal. emit CreatorPaid(creator, balance);
|
function payCreator() internal inState(State.Completed) returns(bool) {
address payable creator = payable(owner());
uint balance = address(this).balance;
goal = balance;
if (creator.send(balance)){
return true;
}
return false;
}
| 6,490,426 |
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./ERC20Impl.sol";
import "./LockRequestable.sol";
/** @title A contact to govern hybrid control over increases to the token supply.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the ‘true’ custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'limited printer') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
* @author Gemini Trust Company, LLC
*/
contract PrintLimiter is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl immutable public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
address immutable public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling.
*/
address immutable public limitedPrinter;
/** @dev The maximum that the token supply can be increased to
* through use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'limited printer' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = _custodian;
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian, "unauthorized");
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter, "unauthorized");
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value, bytes32 _merkleRoot) external onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply, "overflow");
require(newTotalSupply <= totalSupplyCeiling, "ceiling exceeded");
erc20Impl.executePrint(_receiver, _value, _merkleRoot);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) external returns (bytes32 lockId) {
require(_raiseBy != 0, "zero");
(bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId();
lockId = keccak256(
abi.encodePacked(
preLockId,
this.requestCeilingRaise.selector,
_raiseBy
)
);
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy, lockRequestIdx);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) external onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0, "no such lockId");
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the limited printer.
*
* @dev The limited printer is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) external onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling, "overflow");
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) external onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) external onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy, uint256 _lockRequestIdx);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./CustodianUpgradeable.sol";
import "./ERC20Proxy.sol";
import "./ERC20Store.sol";
/** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
* @author Gemini Trust Company, LLC
*/
contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
bytes32 merkleRoot;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy immutable public erc20Proxy;
/// @dev The reference to the store.
ERC20Store immutable public erc20Store;
address immutable public implOwner;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
bytes32 private immutable _PERMIT_TYPEHASH;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _implOwner
)
CustodianUpgradeable(_custodian)
{
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
implOwner = _implOwner;
bytes32 hashedName = keccak256(bytes(ERC20Proxy(_erc20Proxy).name()));
bytes32 hashedVersion = keccak256(bytes("1"));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion, _erc20Proxy);
_TYPE_HASH = typeHash;
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy), "unauthorized");
_;
}
modifier onlyImplOwner {
require(msg.sender == implOwner, "unauthorized");
_;
}
function _approve(
address _owner,
address _spender,
uint256 _amount
)
private
{
require(_spender != address(0), "zero address"); // disallow unspendable approvals
erc20Store.setAllowance(_owner, _spender, _amount);
erc20Proxy.emitApproval(_owner, _spender, _amount);
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
external
onlyProxy
returns (bool success)
{
_approve(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
external
onlyProxy
returns (bool success)
{
require(_spender != address(0), "zero address"); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance, "overflow");
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
external
onlyProxy
returns (bool success)
{
require(_spender != address(0), "zero address"); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance, "overflow");
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(owner != address(0x0), "zero address");
require(block.timestamp <= deadline, "expired");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
erc20Store.getNonceAndIncrement(owner),
deadline
)
);
bytes32 hash = keccak256(
abi.encodePacked(
"\x19\x01",
_domainSeparatorV4(),
structHash
)
);
address signer = ecrecover(hash, v, r, s);
require(signer == owner, "invalid signature");
_approve(owner, spender, value);
}
function nonces(address owner) external view returns (uint256) {
return erc20Store.nonces(owner);
}
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparatorV4();
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value, bytes32 _merkleRoot) external returns (bytes32 lockId) {
require(_receiver != address(0), "zero address");
(bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId();
lockId = keccak256(
abi.encodePacked(
preLockId,
this.requestPrint.selector,
_receiver,
_value,
_merkleRoot
)
);
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value,
merkleRoot: _merkleRoot
});
emit PrintingLocked(lockId, _receiver, _value, lockRequestIdx);
}
function _executePrint(address _receiver, uint256 _value, bytes32 _merkleRoot) private {
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + _value;
if (newSupply >= supply) {
erc20Store.setTotalSupplyAndAddBalance(newSupply, _receiver, _value);
erc20Proxy.emitTransfer(address(0), _receiver, _value);
emit AuditPrint(_merkleRoot);
}
}
function executePrint(address _receiver, uint256 _value, bytes32 _merkleRoot) external onlyCustodian {
_executePrint(_receiver, _value, _merkleRoot);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) external onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0), "no such lockId");
uint256 value = print.value;
bytes32 merkleRoot = print.merkleRoot;
delete pendingPrintMap[_lockId];
emit PrintingConfirmed(_lockId, receiver, value);
_executePrint(receiver, value, merkleRoot);
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value, bytes32 _merkleRoot) external returns (bool success) {
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender, "insufficient balance");
erc20Store.setBalanceAndDecreaseTotalSupply(
msg.sender,
balanceOfSender - _value,
_value
);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
emit AuditBurn(_merkleRoot);
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] calldata _tos, uint256[] calldata _values) external returns (bool success) {
require(_tos.length == _values.length, "inconsistent length");
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0), "zero address");
uint256 v = _values[i];
require(senderBalance >= v, "insufficient balance");
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
external
onlyProxy
returns (bool success)
{
require(_to != address(0), "zero address"); // ensure burn is the cannonical transfer to 0x0
(uint256 balanceOfFrom, uint256 senderAllowance) = erc20Store.balanceAndAllowed(_from, _sender);
require(_value <= balanceOfFrom, "insufficient balance");
require(_value <= senderAllowance, "insufficient allowance");
erc20Store.setBalanceAndAllowanceAndAddBalance(
_from, balanceOfFrom - _value,
_sender, senderAllowance - _value,
_to, _value
);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
external
onlyProxy
returns (bool success)
{
require(_to != address(0), "zero address"); // ensure burn is the cannonical transfer to 0x0
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender, "insufficient balance");
erc20Store.setBalanceAndAddBalance(
_sender, balanceOfSender - _value,
_to, _value
);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() external view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) external view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
function executeCallInProxy(
address contractAddress,
bytes calldata callData
) external onlyImplOwner {
erc20Proxy.executeCallWithData(contractAddress, callData);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() private view returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, address(erc20Proxy));
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version, address verifyingContract) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
verifyingContract
)
);
}
function _getChainId() private view returns (uint256 chainId) {
// SEE:
// - https://github.com/ethereum/solidity/issues/8854#issuecomment-629436203
// - https://github.com/ethereum/solidity/issues/10090
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value, uint256 _lockRequestIdx);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
event AuditBurn(bytes32 merkleRoot);
event AuditPrint(bytes32 merkleRoot);
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./LockRequestable.sol";
/** @title A contract to inherit upgradeable custodianship.
*
* @notice A contract that provides re-usable code for upgradeable
* custodianship. That custodian may be an account or another contract.
*
* @dev This contract is intended to be inherited by any contract
* requiring a custodian to control some aspect of its functionality.
* This contract provides the mechanism for that custodianship to be
* passed from one custodian to the next.
*
* @author Gemini Trust Company, LLC
*/
abstract contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian, "unauthorized");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) external returns (bytes32 lockId) {
require(_proposedCustodian != address(0), "zero address");
(bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId();
lockId = keccak256(
abi.encodePacked(
preLockId,
this.requestCustodianChange.selector,
_proposedCustodian
)
);
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian, lockRequestIdx);
}
/** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) external onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "no such lockId");
return changeRequest.proposedNew;
}
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian,
uint256 _lockRequestIdx
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
/** @title A contract for generating unique identifiers
*
* @notice A contract that provides a identifier generation scheme,
* guaranteeing uniqueness across all contracts that inherit from it,
* as well as unpredictability of future identifiers.
*
* @dev This contract is intended to be inherited by any contract that
* implements the callback software pattern for cooperative custodianship.
*
* @author Gemini Trust Company, LLC
*/
abstract contract LockRequestable {
// MEMBERS
/// @notice the count of all invocations of `generatePreLockId`.
uint256 public lockRequestCount;
// CONSTRUCTOR
constructor() {
lockRequestCount = 0;
}
// FUNCTIONS
/** @notice Returns a fresh unique identifier.
*
* @dev the generation scheme uses three components.
* First, the blockhash of the previous block.
* Second, the deployed address.
* Third, the next value of the counter.
* This ensure that identifiers are unique across all contracts
* following this scheme, and that future identifiers are
* unpredictable.
*
* @return preLockId a 32-byte unique identifier.
* @return lockRequestIdx index of lock request
*/
function generatePreLockId() internal returns (bytes32 preLockId, uint256 lockRequestIdx) {
lockRequestIdx = ++lockRequestCount;
preLockId = keccak256(
abi.encodePacked(
blockhash(block.number - 1),
address(this),
lockRequestIdx
)
);
}
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./EIP2612Interface.sol";
import "./ERC20Interface.sol";
import "./ERC20ImplUpgradeable.sol";
/** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
* @author Gemini Trust Company, LLC
*/
contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable, EIP2612Interface {
// MEMBERS
/// @notice Returns the name of the token.
string public name; // TODO: use `constant` for mainnet
/// @notice Returns the symbol of the token.
string public symbol; // TODO: use `constant` for mainnet
/// @notice Returns the number of decimals the token uses.
uint8 immutable public decimals; // TODO: use `constant` (18) for mainnet
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() external override view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) external override view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) external onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) external override returns (bool success) {
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) external override returns (bool success) {
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) external onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) external override returns (bool success) {
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) external returns (bool success) {
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) external returns (bool success) {
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) external override view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override {
erc20Impl.permit(owner, spender, value, deadline, v, r, s);
}
function nonces(address owner) external override view returns (uint256) {
return erc20Impl.nonces(owner);
}
function DOMAIN_SEPARATOR() external override view returns (bytes32) {
return erc20Impl.DOMAIN_SEPARATOR();
}
function executeCallWithData(address contractAddress, bytes calldata callData) external {
address implAddr = address(erc20Impl);
require(msg.sender == implAddr, "unauthorized");
require(contractAddress != implAddr, "disallowed");
(bool success, bytes memory returnData) = contractAddress.call(callData);
if (success) {
emit CallWithDataSuccess(contractAddress, callData, returnData);
} else {
emit CallWithDataFailure(contractAddress, callData, returnData);
}
}
event CallWithDataSuccess(address contractAddress, bytes callData, bytes returnData);
event CallWithDataFailure(address contractAddress, bytes callData, bytes returnData);
}
// SPDX-License-Identifier: MIT
// Adapted from
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ceb7324657ed4e73df6cb6f853c60c8d3fb3a0e9/contracts/drafts/IERC20Permit.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface EIP2612Interface {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
interface ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() external view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) external view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) external returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) external returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./CustodianUpgradeable.sol";
import "./ERC20Impl.sol";
/** @title A contract to inherit upgradeable token implementations.
*
* @notice A contract that provides re-usable code for upgradeable
* token implementations. It itself inherits from `CustodianUpgradable`
* as the upgrade process is controlled by the custodian.
*
* @dev This contract is intended to be inherited by any contract
* requiring a reference to the active token implementation, either
* to delegate calls to it, or authorize calls from it. This contract
* provides the mechanism for that implementation to be be replaced,
* which constitutes an implementation upgrade.
*
* @author Gemini Trust Company, LLC
*/
abstract contract ERC20ImplUpgradeable is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending implementation changes.
struct ImplChangeRequest {
address proposedNew;
}
// MEMBERS
// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The map of lock ids to pending implementation changes.
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
// CONSTRUCTOR
constructor(address _custodian) CustodianUpgradeable(_custodian) {
erc20Impl = ERC20Impl(0x0);
}
// MODIFIERS
modifier onlyImpl {
require(msg.sender == address(erc20Impl), "unauthorized");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the active implementation associated
* with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedImpl The address of the new active implementation.
* @return lockId A unique identifier for this request.
*/
function requestImplChange(address _proposedImpl) external returns (bytes32 lockId) {
require(_proposedImpl != address(0), "zero address");
(bytes32 preLockId, uint256 lockRequestIdx) = generatePreLockId();
lockId = keccak256(
abi.encodePacked(
preLockId,
this.requestImplChange.selector,
_proposedImpl
)
);
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl, lockRequestIdx);
}
/** @notice Confirms a pending change of the active implementation
* associated with this contract.
*
* @dev When called by the custodian with a lock id associated with a
* pending change, the `ERC20Impl erc20Impl` member will be updated
* with the requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmImplChange(bytes32 _lockId) external onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
// PRIVATE FUNCTIONS
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "no such lockId");
return ERC20Impl(changeRequest.proposedNew);
}
/// @dev Emitted by successful `requestImplChange` calls.
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl,
uint256 _lockRequestIdx
);
/// @dev Emitted by successful `confirmImplChange` calls.
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./ERC20ImplUpgradeable.sol";
/** @title ERC20 compliant token balance store.
*
* @notice This contract serves as the store of balances, allowances, and
* supply for the ERC20 compliant token. No business logic exists here.
*
* @dev This contract contains no business logic and instead
* is the final destination for any change in balances, allowances, or token
* supply. This contract is upgradeable in the sense that its custodian can
* update the `erc20Impl` address, thus redirecting the source of logic that
* determines how the balances will be updated.
*
* @author Gemini Trust Company, LLC
*/
contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// @dev The total token supply.
uint256 public totalSupply;
/// @dev The mapping of balances.
mapping (address => uint256) public balances;
/// @dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
mapping (address => uint256) public nonces;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
/** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
external
onlyImpl
{
allowed[_owner][_spender] = _value;
}
/** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/
function setBalance(
address _owner,
uint256 _newBalance
)
external
onlyImpl
{
balances[_owner] = _newBalance;
}
/** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/
function addBalance(
address _owner,
uint256 _balanceIncrease
)
external
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
function setTotalSupplyAndAddBalance(
uint256 _newTotalSupply,
address _owner,
uint256 _balanceIncrease
)
external
onlyImpl
{
totalSupply = _newTotalSupply;
balances[_owner] = balances[_owner] + _balanceIncrease;
}
function setBalanceAndDecreaseTotalSupply(
address _owner,
uint256 _newBalance,
uint256 _supplyDecrease
)
external
onlyImpl
{
balances[_owner] = _newBalance;
totalSupply = totalSupply - _supplyDecrease;
}
function setBalanceAndAddBalance(
address _ownerToSet,
uint256 _newBalance,
address _ownerToAdd,
uint256 _balanceIncrease
)
external
onlyImpl
{
balances[_ownerToSet] = _newBalance;
balances[_ownerToAdd] = balances[_ownerToAdd] + _balanceIncrease;
}
function setBalanceAndAllowanceAndAddBalance(
address _ownerToSet,
uint256 _newBalance,
address _spenderToSet,
uint256 _newAllowance,
address _ownerToAdd,
uint256 _balanceIncrease
)
external
onlyImpl
{
balances[_ownerToSet] = _newBalance;
allowed[_ownerToSet][_spenderToSet] = _newAllowance;
balances[_ownerToAdd] = balances[_ownerToAdd] + _balanceIncrease;
}
function balanceAndAllowed(
address _owner,
address _spender
)
external
view
returns (uint256 ownerBalance, uint256 spenderAllowance)
{
ownerBalance = balances[_owner];
spenderAllowance = allowed[_owner][_spender];
}
function getNonceAndIncrement(
address _owner
)
external
onlyImpl
returns (uint256 current)
{
current = nonces[_owner];
nonces[_owner] = current + 1;
}
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./ERC20Proxy.sol";
import "./ERC20Impl.sol";
import "./ERC20Store.sol";
contract Initializer {
function initialize(
ERC20Store _store,
ERC20Proxy _proxy,
ERC20Impl _impl,
address _implChangeCustodian,
address _printCustodian) external {
// set impl as active implementation for store and proxy
_store.confirmImplChange(_store.requestImplChange(address(_impl)));
_proxy.confirmImplChange(_proxy.requestImplChange(address(_impl)));
// pass custodianship of store and proxy to impl change custodian
_store.confirmCustodianChange(_store.requestCustodianChange(_implChangeCustodian));
_proxy.confirmCustodianChange(_proxy.requestCustodianChange(_implChangeCustodian));
// pass custodianship of impl to print custodian
_impl.confirmCustodianChange(_impl.requestCustodianChange(_printCustodian));
}
}
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2020 Gemini Trust Company LLC. All Rights Reserved
pragma solidity ^0.7.0;
import "./ERC20Store.sol";
/** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This version of ERC20Impl is intended to revert all ERC20 functions
* that are state mutating; only view functions remain operational. Upgrading
* to this contract places the system into a read-only paused state.
*
* @author Gemini Trust Company, LLC
*/
contract ERC20ImplPaused {
// MEMBERS
/// @dev The reference to the store.
ERC20Store immutable public erc20Store;
// CONSTRUCTOR
constructor(
address _erc20Store
)
{
erc20Store = ERC20Store(_erc20Store);
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() external view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) external view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
}
|
METHODS (ERC20 sub interface impl.) Core logic of the ERC20 `totalSupply` function.
|
function totalSupply() external view returns (uint256) {
return erc20Store.totalSupply();
}
| 11,984,111 |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/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/utils/Pausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* 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());
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
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;
}
}
// 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: contracts/ISparkleTimestamp.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
// import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
// import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
// import "../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
// import "../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
/**
* @dev Sparkle Timestamp Contract
* @author SparkleMobile Inc. (c) 2019-2020
*/
interface ISparkleTimestamp {
/**
* @dev Add new reward timestamp for address
* @param _rewardAddress being added to timestamp collection
*/
function addTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Reset timestamp maturity for loyalty address
* @param _rewardAddress to have reward period reset
*/
function resetTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Zero/delete existing loyalty timestamp entry
* @param _rewardAddress being requested for timestamp deletion
* @notice Test(s) not passed
*/
function deleteTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Get address confirmation for loyalty address
* @param _rewardAddress being queried for address information
*/
function getAddress(address _rewardAddress)
external
returns(address);
/**
* @dev Get timestamp of initial joined timestamp for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getJoinedTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Get timestamp of last deposit for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getDepositTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Get timestamp of reward maturity for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getRewardTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Determine if address specified has a timestamp record
* @param _rewardAddress being queried for timestamp existance
*/
function hasTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Calculate time remaining in seconds until this address' reward matures
* @param _rewardAddress to query remaining time before reward matures
*/
function getTimeRemaining(address _rewardAddress)
external
returns(uint256, bool, uint256);
/**
* @dev Determine if reward is mature for address
* @param _rewardAddress Address requesting addition in to loyalty timestamp collection
*/
function isRewardReady(address _rewardAddress)
external
returns(bool);
/**
* @dev Change the stored loyalty controller contract address
* @param _newAddress of new loyalty controller contract address
*/
function setContractAddress(address _newAddress)
external;
/**
* @dev Return the stored authorized controller address
* @return Address of loyalty controller contract
*/
function getContractAddress()
external
returns(address);
/**
* @dev Change the stored loyalty time period
* @param _newTimePeriod of new reward period (in seconds)
*/
function setTimePeriod(uint256 _newTimePeriod)
external;
/**
* @dev Return the current loyalty timer period
* @return Current stored value of loyalty time period
*/
function getTimePeriod()
external
returns(uint256);
/**
* @dev Event signal: Reset timestamp
*/
event ResetTimestamp(address _rewardAddress);
/**
* @dev Event signal: Loyalty contract address waws changed
*/
event ContractAddressChanged(address indexed _previousAddress, address indexed _newAddress);
/**
* @dev Event signal: Loyalty reward time period was changed
*/
event TimePeriodChanged( uint256 indexed _previousTimePeriod, uint256 indexed _newTimePeriod);
/**
* @dev Event signal: Loyalty reward timestamp was added
*/
event TimestampAdded( address indexed _newTimestampAddress );
/**
* @dev Event signal: Loyalty reward timestamp was removed
*/
event TimestampDeleted( address indexed _newTimestampAddress );
/**
* @dev Event signal: Timestamp for address was reset
*/
event TimestampReset(address _rewardAddress);
}
// File: contracts/ISparkleRewardTiers.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
// import '../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol';
// import '../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol';
// import '../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol';
// import '../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol';
/**
* @title A contract for managing reward tiers
* @author SparkleLoyalty Inc. (c) 2019-2020
*/
// interface ISparkleRewardTiers is Ownable, Pausable, ReentrancyGuard {
interface ISparkleRewardTiers {
/**
* @dev Add a new reward tier to the contract for future proofing
* @param _index of the new reward tier to add
* @param _rate of the added reward tier
* @param _price of the added reward tier
* @param _enabled status of the added reward tier
* @notice Test(s) Need rewrite
*/
function addTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Update an existing reward tier with new values
* @param _index of reward tier to update
* @param _rate of the reward tier
* @param _price of the reward tier
* @param _enabled status of the reward tier
* @return (bool) indicating success/failure
* @notice Test(s) Need rewrite
*/
function updateTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Remove an existing reward tier from list of tiers
* @param _index of reward tier to remove
* @notice Test(s) Need rewrite
*/
function deleteTier(uint256 _index)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Get the rate value of specified tier
* @param _index of tier to query
* @return specified reward tier rate
* @notice Test(s) Need rewrite
*/
function getRate(uint256 _index)
external
// view
// whenNotPaused
returns(uint256);
/**
* @dev Get price of tier
* @param _index of tier to query
* @return uint256 indicating tier price
* @notice Test(s) Need rewrite
*/
function getPrice(uint256 _index)
external
// view
// whenNotPaused
returns(uint256);
/**
* @dev Get the enabled status of tier
* @param _index of tier to query
* @return bool indicating status of tier
* @notice Test(s) Need rewrite
*/
function getEnabled(uint256 _index)
external
// view
// whenNotPaused
returns(bool);
/**
* @dev Withdraw ether that has been sent directly to the contract
* @return bool indicating withdraw success
* @notice Test(s) Need rewrite
*/
function withdrawEth()
external
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Event triggered when a reward tier is deleted
* @param _index of tier to deleted
*/
event TierDeleted(uint256 _index);
/**
* @dev Event triggered when a reward tier is updated
* @param _index of the updated tier
* @param _rate of updated tier
* @param _price of updated tier
* @param _enabled status of updated tier
*/
event TierUpdated(uint256 _index, uint256 _rate, uint256 _price, bool _enabled);
/**
* @dev Event triggered when a new reward tier is added
* @param _index of the tier added
* @param _rate of added tier
* @param _price of added tier
* @param _enabled status of added tier
*/
event TierAdded(uint256 _index, uint256 _rate, uint256 _price, bool _enabled);
}
// File: contracts/SparkleLoyalty.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
/**
* @dev Sparkle Loyalty Rewards
* @author SparkleMobile Inc.
*/
contract SparkleLoyalty is Ownable, Pausable, ReentrancyGuard {
/**
* @dev Ensure math safety through SafeMath
*/
using SafeMath for uint256;
// Gas to send with certain transations that may cost more in the future due to chain growth
uint256 private gasToSendWithTX = 25317;
// Base rate APR (5%) factored to 365.2422 gregorian days
uint256 private baseRate = 0.00041069 * 10e7; // A full year is 365.2422 gregorian days (5%)
// Account data structure
struct Account {
address _address; // Loyalty reward address
uint256 _balance; // Total tokens deposited
uint256 _collected; // Total tokens collected
uint256 _claimed; // Total succesfull reward claims
uint256 _joined; // Total times address has joined
uint256 _tier; // Tier index of reward tier
bool _isLocked; // Is the account locked
}
// tokenAddress of erc20 token address
address private tokenAddress;
// timestampAddress of time stamp contract address
address private timestampAddress;
// treasuryAddress of token treeasury address
address private treasuryAddress;
// collectionAddress to receive eth payed for tier upgrades
address private collectionAddress;
// rewardTiersAddress to resolve reward tier specifications
address private tiersAddress;
// minProofRequired to deposit of rewards to be eligibile
uint256 private minRequired;
// maxProofAllowed for deposit to be eligibile
uint256 private maxAllowed;
// totalTokensClaimed of all rewards awarded
uint256 private totalTokensClaimed;
// totalTimesClaimed of all successfully claimed rewards
uint256 private totalTimesClaimed;
// totalActiveAccounts count of all currently active addresses
uint256 private totalActiveAccounts;
// Accounts mapping of user loyalty records
mapping(address => Account) private accounts;
/**
* @dev Sparkle Loyalty Rewards Program contract .cTor
* @param _tokenAddress of token used for proof of loyalty rewards
* @param _treasuryAddress of proof of loyalty token reward distribution
* @param _collectionAddress of ethereum account to collect tier upgrade eth
* @param _tiersAddress of the proof of loyalty tier rewards support contract
* @param _timestampAddress of the proof of loyalty timestamp support contract
*/
constructor(address _tokenAddress, address _treasuryAddress, address _collectionAddress, address _tiersAddress, address _timestampAddress)
public
Ownable()
Pausable()
ReentrancyGuard()
{
// Initialize contract internal addresse(s) from params
tokenAddress = _tokenAddress;
treasuryAddress = _treasuryAddress;
collectionAddress = _collectionAddress;
tiersAddress = _tiersAddress;
timestampAddress = _timestampAddress;
// Initialize minimum/maximum allowed deposit limits
minRequired = uint256(1000).mul(10e7);
maxAllowed = uint256(250000).mul(10e7);
}
/**
* @dev Deposit additional tokens to a reward address loyalty balance
* @param _depositAmount of tokens to deposit into a reward address balance
* @return bool indicating the success of the deposit operation (true == success)
*/
function depositLoyalty(uint _depositAmount)
public
whenNotPaused
nonReentrant
returns (bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}1');
// Validate specified value meets minimum requirements
require(_depositAmount >= minRequired, 'Minimum required');
// Determine if caller has approved enough allowance for this deposit
if(IERC20(tokenAddress).allowance(msg.sender, address(this)) < _depositAmount) {
// No, rever informing that deposit amount exceeded allownce amount
revert('Exceeds allowance');
}
// Obtain a storage instsance of callers account record
Account storage loyaltyAccount = accounts[msg.sender];
// Determine if there is an upper deposit cap
if(maxAllowed > 0) {
// Yes, determine if the deposit amount + current balance exceed max deposit cap
if(loyaltyAccount._balance.add(_depositAmount) > maxAllowed || _depositAmount > maxAllowed) {
// Yes, revert informing that the maximum deposit cap has been exceeded
revert('Exceeds cap');
}
}
// Determine if the tier selected is enabled
if(!ISparkleRewardTiers(tiersAddress).getEnabled(loyaltyAccount._tier)) {
// No, then this tier cannot be selected
revert('Invalid tier');
}
// Determine of transfer from caller has succeeded
if(IERC20(tokenAddress).transferFrom(msg.sender, address(this), _depositAmount)) {
// Yes, thend determine if the specified address has a timestamp record
if(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender)) {
// Yes, update callers account balance by deposit amount
loyaltyAccount._balance = loyaltyAccount._balance.add(_depositAmount);
// Reset the callers reward timestamp
_resetTimestamp(msg.sender);
//
emit DepositLoyaltyEvent(msg.sender, _depositAmount, true);
// Return success
return true;
}
// Determine if a timestamp has been added for caller
if(!ISparkleTimestamp(timestampAddress).addTimestamp(msg.sender)) {
// No, revert indicating there was some kind of error
revert('No timestamp created');
}
// Prepare loyalty account record
loyaltyAccount._address = address(msg.sender);
loyaltyAccount._balance = _depositAmount;
loyaltyAccount._joined = loyaltyAccount._joined.add(1);
// Update global account counter
totalActiveAccounts = totalActiveAccounts.add(1);
//
emit DepositLoyaltyEvent(msg.sender, _depositAmount, false);
// Return success
return true;
}
// Return failure
return false;
}
/**
* @dev Claim Sparkle Loyalty reward
*/
function claimLoyaltyReward()
public
whenNotPaused
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Validate caller has a timestamp and it has matured
require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No record');
require(ISparkleTimestamp(timestampAddress).isRewardReady(msg.sender), 'Not mature');
// Obtain the current state of the callers timestamp
(uint256 timeRemaining, bool isReady, uint256 rewardDate) = ISparkleTimestamp(timestampAddress).getTimeRemaining(msg.sender);
// Determine if the callers reward has matured
if(isReady) {
// Value not used but throw unused var warning (cleanup)
rewardDate = 0;
// Yes, then obtain a storage instance of callers account record
Account storage loyaltyAccount = accounts[msg.sender];
// Obtain values required for caculations
uint256 dayCount = (timeRemaining.div(ISparkleTimestamp(timestampAddress).getTimePeriod())).add(1);
uint256 tokenBalance = loyaltyAccount._balance.add(loyaltyAccount._collected);
uint256 rewardRate = ISparkleRewardTiers(tiersAddress).getRate(loyaltyAccount._tier);
uint256 rewardTotal = baseRate.mul(tokenBalance).mul(rewardRate).mul(dayCount).div(10e7).div(10e7);
// Increment collected by reward total
loyaltyAccount._collected = loyaltyAccount._collected.add(rewardTotal);
// Increment total number of times a reward has been claimed
loyaltyAccount._claimed = loyaltyAccount._claimed.add(1);
// Incrememtn total number of times rewards have been collected by all
totalTimesClaimed = totalTimesClaimed.add(1);
// Increment total number of tokens claimed
totalTokensClaimed += rewardTotal;
// Reset the callers timestamp record
_resetTimestamp(msg.sender);
// Emit event log to the block chain for future web3 use
emit RewardClaimedEvent(msg.sender, rewardTotal);
// Return success
return true;
}
// Revert opposed to returning boolean (May or may not return a txreceipt)
revert('Failed claim');
}
/**
* @dev Withdraw the current deposit balance + any earned loyalty rewards
*/
function withdrawLoyalty()
public
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No timestamp2');
// Determine if the account has been locked
if(accounts[msg.sender]._isLocked) {
// Yes, revert informing that this loyalty account has been locked
revert('Locked');
}
// Obtain values needed from account record before zeroing
uint256 joinCount = accounts[msg.sender]._joined;
uint256 collected = accounts[msg.sender]._collected;
uint256 deposit = accounts[msg.sender]._balance;
bool isLocked = accounts[msg.sender]._isLocked;
// Zero out the callers account record
Account storage account = accounts[msg.sender];
account._address = address(0x0);
account._balance = 0x0;
account._collected = 0x0;
account._joined = joinCount;
account._claimed = 0x0;
account._tier = 0x0;
// Preserve account lock even after withdraw (account always locked)
account._isLocked = isLocked;
// Decement the total number of active accounts
totalActiveAccounts = totalActiveAccounts.sub(1);
// Delete the callers timestamp record
_deleteTimestamp(msg.sender);
// Determine if transfer from treasury address is a success
if(!IERC20(tokenAddress).transferFrom(treasuryAddress, msg.sender, collected)) {
// No, revert indicating that the transfer and wisthdraw has failed
revert('Withdraw failed');
}
// Determine if transfer from contract address is a sucess
if(!IERC20(tokenAddress).transfer(msg.sender, deposit)) {
// No, revert indicating that the treansfer and withdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyWithdrawnEvent(msg.sender, deposit.add(collected));
}
function returnLoyaltyDeposit(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 deposit = accounts[_rewardAddress]._balance;
Account storage account = accounts[_rewardAddress];
account._balance = 0x0;
// Determine if transfer from contract address is a sucess
if(!IERC20(tokenAddress).transfer(_rewardAddress, deposit)) {
// No, revert indicating that the treansfer and withdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyDepositWithdrawnEvent(_rewardAddress, deposit);
}
function returnLoyaltyCollected(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 collected = accounts[_rewardAddress]._collected;
Account storage account = accounts[_rewardAddress];
account._collected = 0x0;
// Determine if transfer from treasury address is a success
if(!IERC20(tokenAddress).transferFrom(treasuryAddress, _rewardAddress, collected)) {
// No, revert indicating that the transfer and wisthdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyCollectedWithdrawnEvent(_rewardAddress, collected);
}
function removeLoyaltyAccount(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 joinCount = accounts[_rewardAddress]._joined;
Account storage account = accounts[_rewardAddress];
account._address = address(0x0);
account._balance = 0x0;
account._collected = 0x0;
account._joined = joinCount;
account._claimed = 0x0;
account._tier = 0x0;
account._isLocked = false;
// Decement the total number of active accounts
totalActiveAccounts = totalActiveAccounts.sub(1);
// Delete the callers timestamp record
_deleteTimestamp(_rewardAddress);
emit LoyaltyAccountRemovedEvent(_rewardAddress);
}
/**
* @dev Gets the locked status of the specified address
* @param _loyaltyAddress of account
* @return (bool) indicating locked status
*/
function isLocked(address _loyaltyAddress)
public
view
whenNotPaused
returns (bool)
{
return accounts[_loyaltyAddress]._isLocked;
}
function lockAccount(address _rewardAddress, bool _value)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
require(_rewardAddress != address(0x0), 'Invalid {reward}');
// Validate specified address has timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timstamp');
// Set the specified address' locked status
accounts[_rewardAddress]._isLocked = _value;
// Emit event log to the block chain for future web3 use
emit LockedAccountEvent(_rewardAddress, _value);
}
/**
* @dev Gets the storage address value of the specified address
* @param _loyaltyAddress of account
* @return (address) indicating the address stored calls account record
*/
function getLoyaltyAddress(address _loyaltyAddress)
public
view
whenNotPaused
returns(address)
{
return accounts[_loyaltyAddress]._address;
}
/**
* @dev Get the deposit balance value of specified address
* @param _loyaltyAddress of account
* @return (uint256) indicating the balance value
*/
function getDepositBalance(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._balance;
}
/**
* @dev Get the tokens collected by the specified address
* @param _loyaltyAddress of account
* @return (uint256) indicating the tokens collected
*/
function getTokensCollected(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._collected;
}
/**
* @dev Get the total balance (deposit + collected) of tokens
* @param _loyaltyAddress of account
* @return (uint256) indicating total balance
*/
function getTotalBalance(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._balance.add(accounts[_loyaltyAddress]._collected);
}
/**
* @dev Get the times loyalty has been claimed
* @param _loyaltyAddress of account
* @return (uint256) indicating total time claimed
*/
function getTimesClaimed(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._claimed;
}
/**
* @dev Get total number of times joined
* @param _loyaltyAddress of account
* @return (uint256)
*/
function getTimesJoined(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._joined;
}
/**
* @dev Get time remaining before reward maturity
* @param _loyaltyAddress of account
* @return (uint256, bool) Indicating time remaining/past and boolean indicating maturity
*/
function getTimeRemaining(address _loyaltyAddress)
public
whenNotPaused
returns (uint256, bool, uint256)
{
(uint256 remaining, bool status, uint256 deposit) = ISparkleTimestamp(timestampAddress).getTimeRemaining(_loyaltyAddress);
return (remaining, status, deposit);
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
* @param _loyaltyAddress of account
* @return Total number of tokens that have been claimed by users
* @notice Test(s) Not written
*/
function getRewardTier(address _loyaltyAddress)
public
view whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._tier;
}
/**
* @dev Select reward tier for msg.sender
* @param _tierSelected id of the reward tier interested in purchasing
* @return (bool) indicating failure/success
*/
function selectRewardTier(uint256 _tierSelected)
public
payable
whenNotPaused
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address has a timestamp
require(accounts[msg.sender]._address == address(msg.sender), 'No timestamp3');
// Validate tier selection
require(accounts[msg.sender]._tier != _tierSelected, 'Already selected');
// Validate that ether was sent with the call
require(msg.value > 0, 'No ether');
// Determine if the specified rate is > than existing rate
if(ISparkleRewardTiers(tiersAddress).getRate(accounts[msg.sender]._tier) >= ISparkleRewardTiers(tiersAddress).getRate(_tierSelected)) {
// No, revert indicating failure
revert('Invalid tier');
}
// Determine if ether transfer for tier upgrade has completed successfully
(bool success, ) = address(collectionAddress).call{value: ISparkleRewardTiers(tiersAddress).getPrice(_tierSelected), gas: gasToSendWithTX}('');
require(success, 'Rate unchanged');
// Update callers rate with the new selected rate
accounts[msg.sender]._tier = _tierSelected;
emit TierSelectedEvent(msg.sender, _tierSelected);
// Return success
return true;
}
function getRewardTiersAddress()
public
view
whenNotPaused
returns(address)
{
return tiersAddress;
}
/**
* @dev Set tier collectionm address
* @param _newAddress of new collection address
* @notice Test(s) not written
*/
function setRewardTiersAddress(address _newAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address is valid
require(_newAddress != address(0), 'Invalid {reward}');
// Set tier rewards contract address
tiersAddress = _newAddress;
emit TiersAddressChanged(_newAddress);
}
function getCollectionAddress()
public
view
whenNotPaused
returns(address)
{
return collectionAddress;
}
/** @notice Test(s) passed
* @dev Set tier collectionm address
* @param _newAddress of new collection address
*/
function setCollectionAddress(address _newAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address is valid
require(_newAddress != address(0), 'Invalid {collection}');
// Set tier collection address
collectionAddress = _newAddress;
emit CollectionAddressChanged(_newAddress);
}
function getTreasuryAddress()
public
view
whenNotPaused
returns(address)
{
return treasuryAddress;
}
/**
* @dev Set treasury address
* @param _newAddress of the treasury address
* @notice Test(s) passed
*/
function setTreasuryAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Validate specified address
require(_newAddress != address(0), "Invalid {treasury}");
// Set current treasury contract address
treasuryAddress = _newAddress;
emit TreasuryAddressChanged(_newAddress);
}
function getTimestampAddress()
public
view
whenNotPaused
returns(address)
{
return timestampAddress;
}
/**
* @dev Set the timestamp address
* @param _newAddress of timestamp address
* @notice Test(s) passed
*/
function setTimestampAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Set current timestamp contract address
timestampAddress = _newAddress;
emit TimestampAddressChanged(_newAddress);
}
function getTokenAddress()
public
view
whenNotPaused
returns(address)
{
return tokenAddress;
}
/**
* @dev Set the loyalty token address
* @param _newAddress of the new token address
* @notice Test(s) passed
*/
function setTokenAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Set current token contract address
tokenAddress = _newAddress;
emit TokenAddressChangedEvent(_newAddress);
}
function getSentGasAmount()
public
view
whenNotPaused
returns(uint256)
{
return gasToSendWithTX;
}
function setSentGasAmount(uint256 _amount)
public
onlyOwner
whenNotPaused
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Set the current minimum deposit allowed
gasToSendWithTX = _amount;
emit GasSentChanged(_amount);
}
function getBaseRate()
public
view
whenNotPaused
returns(uint256)
{
return baseRate;
}
function setBaseRate(uint256 _newRate)
public
onlyOwner
whenNotPaused
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Set the current minimum deposit allowed
baseRate = _newRate;
emit BaseRateChanged(_newRate);
}
/**
* @dev Set the minimum Proof Of Loyalty amount allowed for deposit
* @param _minProof amount for new minimum accepted loyalty reward deposit
* @notice _minProof value is multiplied internally by 10e7. Do not multiply before calling!
*/
function setMinProof(uint256 _minProof)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Validate specified minimum is not lower than 1000 tokens
require(_minProof >= 1000, 'Invalid amount');
// Set the current minimum deposit allowed
minRequired = _minProof.mul(10e7);
emit MinProofChanged(minRequired);
}
event MinProofChanged(uint256);
/**
* @dev Get the minimum Proof Of Loyalty amount allowed for deposit
* @return Amount of tokens required for Proof Of Loyalty Rewards
* @notice Test(s) passed
*/
function getMinProof()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating minimum deposit allowed
return minRequired;
}
/**
* @dev Set the maximum Proof Of Loyalty amount allowed for deposit
* @param _maxProof amount for new maximum loyalty reward deposit
* @notice _maxProof value is multiplied internally by 10e7. Do not multiply before calling!
* @notice Smallest maximum value is 1000 + _minProof amount. (Ex: If _minProof == 1000 then smallest _maxProof possible is 2000)
*/
function setMaxProof(uint256 _maxProof)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
require(_maxProof >= 2000, 'Invalid amount');
// Set allow maximum deposit
maxAllowed = _maxProof.mul(10e7);
}
/**
* @dev Get the maximum Proof Of Loyalty amount allowed for deposit
* @return Maximum amount of tokens allowed for Proof Of Loyalty deposit
* @notice Test(s) passed
*/
function getMaxProof()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating current allowed maximum deposit
return maxAllowed;
}
/**
* @dev Get the total number of tokens claimed by all users
* @return Total number of tokens that have been claimed by users
* @notice Test(s) Not written
*/
function getTotalTokensClaimed()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating total number of tokens that have been claimed by all
return totalTokensClaimed;
}
/**
* @dev Get total number of times rewards have been claimed for all users
* @return Total number of times rewards have been claimed
*/
function getTotalTimesClaimed()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating total number of tokens that have been claimed by all
return totalTimesClaimed;
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
*/
function withdrawEth(address _toAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_toAddress != address(0x0), 'Invalid {to}');
// Validate there is ether to withdraw
require(address(this).balance > 0, 'No ether');
// Determine if ether transfer of stored ether has completed successfully
// require(address(_toAddress).call.value(address(this).balance).gas(gasToSendWithTX)(), 'Withdraw failed');
(bool success, ) = address(_toAddress).call{value:address(this).balance, gas: gasToSendWithTX}('');
require(success, 'Withdraw failed');
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
* @param _toAddress to receive any stored token balance
*/
function withdrawTokens(address _toAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_toAddress != address(0), "Invalid {to}");
// Validate there are tokens to withdraw
uint256 balance = IERC20(tokenAddress).balanceOf(address(this));
require(balance != 0, "No tokens");
// Validate the transfer of tokens completed successfully
if(IERC20(tokenAddress).transfer(_toAddress, balance)) {
emit TokensWithdrawn(_toAddress, balance);
}
}
/**
* @dev Override loyalty account tier by contract owner
* @param _loyaltyAccount loyalty account address to tier override
* @param _tierSelected reward tier to override current tier value
* @return (bool) indicating success status
*/
function overrideRewardTier(address _loyaltyAccount, uint256 _tierSelected)
public
whenNotPaused
onlyOwner
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
require(_loyaltyAccount != address(0x0), 'Invalid {account}');
// Validate specified address has a timestamp
require(accounts[_loyaltyAccount]._address == address(_loyaltyAccount), 'No timestamp4');
// Update the specified loyalty address tier reward index
accounts[_loyaltyAccount]._tier = _tierSelected;
emit RewardTierChanged(_loyaltyAccount, _tierSelected);
}
/**
* @dev Reset the specified loyalty account timestamp
* @param _rewardAddress of the loyalty account to perfornm a reset
*/
function _resetTimestamp(address _rewardAddress)
internal
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_rewardAddress != address(0), "Invalid {reward}");
// Reset callers timestamp for specified address
require(ISparkleTimestamp(timestampAddress).resetTimestamp(_rewardAddress), 'Reset failed');
emit ResetTimestampEvent(_rewardAddress);
}
/**
* @dev Delete the specified loyalty account timestamp
* @param _rewardAddress of the loyalty account to perfornm the delete
*/
function _deleteTimestamp(address _rewardAddress)
internal
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}16');
// Validate specified address
require(_rewardAddress != address(0), "Invalid {reward}");
// Delete callers timestamp for specified address
require(ISparkleTimestamp(timestampAddress).deleteTimestamp(_rewardAddress), 'Delete failed');
emit DeleteTimestampEvent(_rewardAddress);
}
/**
* @dev Event signal: Treasury address updated
*/
event TreasuryAddressChanged(address);
/**
* @dev Event signal: Timestamp address updated
*/
event TimestampAddressChanged(address);
/**
* @dev Event signal: Token address updated
*/
event TokenAddressChangedEvent(address);
/**
* @dev Event signal: Timestamp reset
*/
event ResetTimestampEvent(address _rewardAddress);
/**
* @dev Event signal: Timestamp deleted
*/
event DeleteTimestampEvent(address _rewardAddress);
/**
* @dev Event signal: Loyalty deposited event
*/
event DepositLoyaltyEvent(address, uint256, bool);
/**
* @dev Event signal: Reward claimed successfully for address
*/
event RewardClaimedEvent(address, uint256);
/**
* @dev Event signal: Loyalty withdrawn
*/
event LoyaltyWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Account locked/unlocked
*/
event LockedAccountEvent(address _rewardAddress, bool _locked);
/**
* @dev Event signal: Loyalty deposit balance withdrawn
*/
event LoyaltyDepositWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Loyalty collected balance withdrawn
*/
event LoyaltyCollectedWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Loyalty account removed
*/
event LoyaltyAccountRemovedEvent(address);
/**
* @dev Event signal: Gas sent with call.value amount updated
*/
event GasSentChanged(uint256);
/**
* @dev Event signal: Reward tiers address updated
*/
event TierSelectedEvent(address, uint256);
/**
* @dev Event signal: Reward tiers address updated
*/
event TiersAddressChanged(address);
/**
* @dev Event signal: Reward tier has been updated
*/
event RewardTierChanged(address, uint256);
/**
* @dev Event signal: Collection address updated
*/
event CollectionAddressChanged(address);
/**
* @dev Event signal: All stored tokens have been removed
*/
event TokensWithdrawn(address, uint256);
/**
* @dev Event signal: Apr base rate has been changed
*/
event BaseRateChanged(uint256);
}
|
Set the maximum Proof Of Loyalty amount allowed for deposit _maxProof amount for new maximum loyalty reward deposit _maxProof value is multiplied internally by 10e7. Do not multiply before calling! Smallest maximum value is 1000 + _minProof amount. (Ex: If _minProof == 1000 then smallest _maxProof possible is 2000)/ Validate calling address (msg.sender) Set allow maximum deposit
|
function setMaxProof(uint256 _maxProof)
public
onlyOwner
whenNotPaused
nonReentrant
{
require(_maxProof >= 2000, 'Invalid amount');
maxAllowed = _maxProof.mul(10e7);
}
| 6,070,153 |
pragma solidity ^0.4.0;
import "./Bits.sol";
import "./ByteUtils.sol";
import "./ECRecovery.sol";
import "./Eip712StructHash.sol";
import "./Math.sol";
import "./Merkle.sol";
import "./PlasmaCore.sol";
import "./PriorityQueue.sol";
import "./PriorityQueueFactory.sol";
import "./RLP.sol";
import "./ERC20.sol";
/**
* @title RootChain
* @dev Represents a MoreVP Plasma chain.
*/
contract RootChain {
using Bits for uint192;
using Bits for uint256;
using ByteUtils for bytes;
using RLP for bytes;
using RLP for RLP.RLPItem;
using PlasmaCore for bytes;
using PlasmaCore for PlasmaCore.TransactionInput;
using PlasmaCore for uint192;
using PlasmaCore for uint256;
/*
* Storage
*/
uint256 constant public CHILD_BLOCK_INTERVAL = 1000;
// Applies to outputs too
uint8 constant public MAX_INPUTS = 4;
// WARNING: These placeholder bond values are entirely arbitrary.
uint256 public standardExitBond = 31415926535 wei;
uint256 public inFlightExitBond = 31415926535 wei;
uint256 public piggybackBond = 31415926535 wei;
// NOTE: this is the "middle" period. Exit period for fresh utxos we'll double that while IFE phase is half that
uint256 public minExitPeriod;
address public operator;
uint256 public nextChildBlock;
uint256 public nextDepositBlock;
uint256 public nextFeeExit;
mapping (uint256 => Block) public blocks;
mapping (uint192 => Exit) public exits;
mapping (uint192 => InFlightExit) public inFlightExits;
mapping (address => address) public exitsQueues;
bytes32[16] zeroHashes;
struct Block {
bytes32 root;
uint256 timestamp;
}
struct Exit {
address owner;
address token;
uint256 amount;
uint192 position;
}
struct InFlightExit {
uint256 exitStartTimestamp;
uint256 exitPriority;
uint256 exitMap;
PlasmaCore.TransactionOutput[MAX_INPUTS] inputs;
PlasmaCore.TransactionOutput[MAX_INPUTS] outputs;
address bondOwner;
uint256 oldestCompetitor;
}
struct _InputSum {
address token;
uint256 amount;
}
/*
* Events
*/
event BlockSubmitted(
uint256 blockNumber
);
event TokenAdded(
address token
);
event DepositCreated(
address indexed depositor,
uint256 indexed blknum,
address indexed token,
uint256 amount
);
event ExitStarted(
address indexed owner,
uint192 exitId
);
event ExitFinalized(
uint192 indexed exitId
);
event ExitChallenged(
uint256 indexed utxoPos
);
event InFlightExitStarted(
address indexed initiator,
bytes32 txHash
);
event InFlightExitPiggybacked(
address indexed owner,
bytes32 txHash,
uint8 outputIndex
);
event InFlightExitChallenged(
address indexed challenger,
bytes32 txHash,
uint256 challengeTxPosition
);
event InFlightExitChallengeResponded(
address challenger,
bytes32 txHash,
uint256 challengeTxPosition
);
event InFlightExitOutputBlocked(
address indexed challenger,
bytes32 txHash,
uint8 outputIndex
);
event InFlightExitFinalized(
uint192 inFlightExitId,
uint8 outputIndex
);
/*
* Modifiers
*/
modifier onlyOperator() {
require(msg.sender == operator);
_;
}
modifier onlyWithValue(uint256 _value) {
require(msg.value == _value);
_;
}
/*
* Empty, check `function init()`
*/
constructor()
public
{
}
/*
* Public functions
*/
/**
* @dev Required to be called before any operations on the contract
* Split from `constructor` to fit into block gas limit
* @param _minExitPeriod standard exit period in seconds
*/
function init(uint256 _minExitPeriod)
public
{
_initOperator();
minExitPeriod = _minExitPeriod;
nextChildBlock = CHILD_BLOCK_INTERVAL;
nextDepositBlock = 1;
nextFeeExit = 1;
// Support only ETH on deployment; other tokens need
// to be added explicitly.
exitsQueues[address(0)] = PriorityQueueFactory.deploy(this);
// Pre-compute some hashes to save gas later.
bytes32 zeroHash = keccak256(abi.encodePacked(uint256(0)));
for (uint i = 0; i < 16; i++) {
zeroHashes[i] = zeroHash;
zeroHash = keccak256(abi.encodePacked(zeroHash, zeroHash));
}
}
// @dev Allows anyone to add new token to Plasma chain
// @param token The address of the ERC20 token
function addToken(address _token)
public
{
require(!hasToken(_token));
exitsQueues[_token] = PriorityQueueFactory.deploy(this);
emit TokenAdded(_token);
}
/**
* @dev Allows the operator to submit a child block.
* @param _blockRoot Merkle root of the block.
*/
function submitBlock(bytes32 _blockRoot)
public
onlyOperator
{
uint256 submittedBlockNumber = nextChildBlock;
// Create the block.
blocks[submittedBlockNumber] = Block({
root: _blockRoot,
timestamp: block.timestamp
});
// Update the next child and deposit blocks.
nextChildBlock += CHILD_BLOCK_INTERVAL;
nextDepositBlock = 1;
emit BlockSubmitted(submittedBlockNumber);
}
/**
* @dev Allows a user to submit a deposit.
* @param _depositTx RLP encoded transaction to act as the deposit.
*/
function deposit(bytes _depositTx)
public
payable
{
// Only allow a limited number of deposits per child block.
require(nextDepositBlock < CHILD_BLOCK_INTERVAL);
// Decode the transaction.
PlasmaCore.Transaction memory decodedTx = _depositTx.decode();
// Check that the first output has the correct balance.
require(decodedTx.outputs[0].amount == msg.value);
// Check that the first output has correct currency (ETH).
require(decodedTx.outputs[0].token == address(0));
// Perform other checks and create a deposit block.
_processDeposit(_depositTx, decodedTx);
}
/**
* @dev Deposits approved amount of ERC20 token. Approve must be called first. Note: does not check if token was added.
* @param _depositTx RLP encoded transaction to act as the deposit.
*/
function depositFrom(bytes _depositTx)
public
{
// Only allow up to CHILD_BLOCK_INTERVAL deposits per child block.
require(nextDepositBlock < CHILD_BLOCK_INTERVAL);
// Decode the transaction.
PlasmaCore.Transaction memory decodedTx = _depositTx.decode();
// Warning, check your ERC20 implementation. TransferFrom should return bool
require(ERC20(decodedTx.outputs[0].token).transferFrom(msg.sender, address(this), decodedTx.outputs[0].amount));
// Perform other checks and create a deposit block.
_processDeposit(_depositTx, decodedTx);
}
function _processDeposit(bytes _depositTx, PlasmaCore.Transaction memory decodedTx)
internal
{
// Following check is needed since _processDeposit
// can be called on stack unwinding during re-entrance attack,
// with nextDepositBlock == 999, producing
// deposit with blknum ending with 000.
require(nextDepositBlock < CHILD_BLOCK_INTERVAL);
for (uint i = 0; i < MAX_INPUTS; i++) {
// all inputs should be empty
require(decodedTx.inputs[i].blknum == 0);
// only first output should have value
if (i >= 1) {
require(decodedTx.outputs[i].amount == 0);
}
}
// Calculate the block root.
bytes32 root = keccak256(_depositTx);
for (i = 0; i < 16; i++) {
root = keccak256(abi.encodePacked(root, zeroHashes[i]));
}
// Insert the deposit block.
uint256 blknum = getDepositBlockNumber();
blocks[blknum] = Block({
root: root,
timestamp: block.timestamp
});
emit DepositCreated(
decodedTx.outputs[0].owner,
blknum,
decodedTx.outputs[0].token,
decodedTx.outputs[0].amount
);
nextDepositBlock++;
}
/**
* @dev Starts a standard withdrawal of a given output. Uses output-age priority.
Crosschecks in-flight exit existence.
NOTE: requires the exiting UTXO's token to be added via `addToken`
* @param _utxoPos Position of the exiting output.
* @param _outputTx RLP encoded transaction that created the exiting output.
* @param _outputTxInclusionProof A Merkle proof showing that the transaction was included.
*/
function startStandardExit(uint192 _utxoPos, bytes _outputTx, bytes _outputTxInclusionProof)
public
payable
onlyWithValue(standardExitBond)
{
// Check that the output transaction actually created the output.
require(_transactionIncluded(_outputTx, _utxoPos, _outputTxInclusionProof));
// Decode the output ID.
uint8 oindex = uint8(_utxoPos.getOindex());
// Parse outputTx.
PlasmaCore.TransactionOutput memory output = _outputTx.getOutput(oindex);
// Only output owner can start an exit.
require(msg.sender == output.owner);
uint192 exitId = getStandardExitId(_outputTx, _utxoPos);
// Make sure this exit is valid.
require(output.amount > 0);
require(exits[exitId].amount == 0);
InFlightExit storage inFlightExit = _getInFlightExit(_outputTx);
// Check whether IFE is either ongoing or finished
if (inFlightExit.exitStartTimestamp != 0 || isFinalized(inFlightExit)) {
// Check if this output was piggybacked or exited in an in-flight exit
require(!isPiggybacked(inFlightExit, oindex + MAX_INPUTS) && !isExited(inFlightExit, oindex + MAX_INPUTS));
// Prevent future piggybacks on this output
setExited(inFlightExit, oindex + MAX_INPUTS);
}
// Determine the exit's priority.
uint256 exitPriority = getStandardExitPriority(exitId, _utxoPos);
// Enqueue the exit into the queue and update the exit mapping.
_enqueueExit(output.token, exitPriority);
exits[exitId] = Exit({
owner: output.owner,
token: output.token,
amount: output.amount,
position: _utxoPos
});
emit ExitStarted(output.owner, exitId);
}
/**
* @dev Blocks a standard exit by showing the exiting output was spent.
* @param _standardExitId Identifier of the standard exit to challenge.
* @param _challengeTx RLP encoded transaction that spends the exiting output.
* @param _inputIndex Which input of the challenging tx corresponds to the exiting output.
* @param _challengeTxSig Signature from the exiting output owner over the spend.
*/
function challengeStandardExit(uint192 _standardExitId, bytes _challengeTx, uint8 _inputIndex, bytes _challengeTxSig)
public
{
// Check that the output is being used as an input to the challenging tx.
uint256 challengedUtxoPos = _challengeTx.getInputUtxoPosition(_inputIndex);
require(challengedUtxoPos == exits[_standardExitId].position);
// Check if exit exists.
address owner = exits[_standardExitId].owner;
// Check that the challenging tx is signed by the output's owner.
require(owner == ECRecovery.recover(Eip712StructHash.hash(_challengeTx), _challengeTxSig));
_processChallengeStandardExit(challengedUtxoPos, _standardExitId);
}
function _cleanupDoubleSpendingStandardExits(uint256 _utxoPos, bytes _txbytes)
internal
returns (bool)
{
uint192 standardExitId = getStandardExitId(_txbytes, _utxoPos);
if (exits[standardExitId].owner != address(0)) {
_processChallengeStandardExit(_utxoPos, standardExitId);
return false;
}
return exits[standardExitId].amount != 0;
}
function _processChallengeStandardExit(uint256 _utxoPos, uint192 _exitId)
internal
{
// Delete the exit.
delete exits[_exitId];
// Send a bond to the challenger.
msg.sender.transfer(standardExitBond);
emit ExitChallenged(_utxoPos);
}
/**
* @dev Allows the operator withdraw any allotted fees. Starts an exit to avoid theft.
* @param _token Token to withdraw.
* @param _amount Amount in fees to withdraw.
*/
function startFeeExit(address _token, uint256 _amount)
public
payable
onlyOperator
onlyWithValue(standardExitBond)
{
// Make sure queue for this token exists.
require(hasToken(_token));
// Make sure this exit is valid.
require(_amount > 0);
uint192 exitId = getFeeExitId(nextFeeExit);
// Determine the exit's priority.
uint256 exitPriority = getFeeExitPriority(exitId);
// Insert the exit into the queue and update the exit mapping.
PriorityQueue queue = PriorityQueue(exitsQueues[_token]);
queue.insert(exitPriority);
exits[exitId] = Exit({
owner: operator,
token: _token,
amount: _amount,
position: uint192(nextFeeExit)
});
nextFeeExit++;
emit ExitStarted(operator, exitId);
}
/**
* @dev Starts an exit for an in-flight transaction.
* @param _inFlightTx RLP encoded in-flight transaction.
* @param _inputTxs Transactions that created the inputs to the in-flight transaction.
* @param _inputTxsInclusionProofs Merkle proofs that show the input-creating transactions are valid.
* @param _inFlightTxSigs Signatures from the owners of each input.
*/
function startInFlightExit(
bytes _inFlightTx,
bytes _inputTxs,
bytes _inputTxsInclusionProofs,
bytes _inFlightTxSigs
)
public
payable
onlyWithValue(inFlightExitBond)
{
// Check if there is an active in-flight exit from this transaction?
InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx);
require(inFlightExit.exitStartTimestamp == 0);
// Check if such an in-flight exit has already been finalized
require(!isFinalized(inFlightExit));
// Separate the inputs transactions.
RLP.RLPItem[] memory splitInputTxs = _inputTxs.toRLPItem().toList();
uint256 [] memory inputTxoPos = new uint256[](splitInputTxs.length);
uint256 youngestInputTxoPos;
bool finalized;
bool any_finalized = false;
for (uint8 i = 0; i < MAX_INPUTS; i++) {
if (_inFlightTx.getInputUtxoPosition(i) == 0) break;
(inFlightExit.inputs[i], inputTxoPos[i], finalized) = _getInputInfo(
_inFlightTx, splitInputTxs[i].toBytes(), _inputTxsInclusionProofs, _inFlightTxSigs.sliceSignature(i), i
);
youngestInputTxoPos = Math.max(youngestInputTxoPos, inputTxoPos[i]);
any_finalized = any_finalized || finalized;
// check whether IFE spends one UTXO twice
for (uint8 j = 0; j < i; ++j){
require(inputTxoPos[i] != inputTxoPos[j]);
}
}
// Validate sums of inputs against sum of outputs token-wise
_validateInputsOutputsSumUp(inFlightExit, _inFlightTx);
// Update the exit mapping.
inFlightExit.bondOwner = msg.sender;
inFlightExit.exitStartTimestamp = block.timestamp;
inFlightExit.exitPriority = getInFlightExitPriority(_inFlightTx, youngestInputTxoPos);
// If any of the inputs were finalized via standard exit, consider it non-canonical
// and flag as not taking part in further canonicity game.
if (any_finalized) {
setNonCanonical(inFlightExit);
}
emit InFlightExitStarted(msg.sender, keccak256(_inFlightTx));
}
function _enqueueExit(address _token, uint256 _exitPriority)
private
{
// Make sure queue for this token exists.
require(hasToken(_token));
PriorityQueue queue = PriorityQueue(exitsQueues[_token]);
queue.insert(_exitPriority);
}
/**
* @dev Allows a user to piggyback onto an in-flight transaction.
NOTE: requires the exiting UTXO's token to be added via `addToken`
* @param _inFlightTx RLP encoded in-flight transaction.
* @param _outputIndex Index of the input/output to piggyback (0-7).
*/
function piggybackInFlightExit(
bytes _inFlightTx,
uint8 _outputIndex
)
public
payable
onlyWithValue(piggybackBond)
{
bytes32 txhash = keccak256(_inFlightTx);
// Check that the output index is valid.
require(_outputIndex < 8);
// Check if SE from the output is not started nor finalized
if (_outputIndex >= MAX_INPUTS) {
// Note that we cannot in-flight exit from a deposit, therefore here the output of the transaction
// cannot be an output of deposit, so we do not have to use `getStandardExitId` (we actually cannot
// as an output of IFE does not have utxoPos)
require(exits[_computeStandardExitId(txhash, _outputIndex - MAX_INPUTS)].amount == 0);
}
// Check that the in-flight exit is active and in period 1.
InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx);
require(_firstPhaseNotOver(inFlightExit));
// Check that we're not piggybacking something that's already been piggybacked.
require(!isPiggybacked(inFlightExit, _outputIndex));
// Check that the message sender owns the output.
PlasmaCore.TransactionOutput memory output;
if (_outputIndex < MAX_INPUTS) {
output = inFlightExit.inputs[_outputIndex];
} else {
output = _inFlightTx.getOutput(_outputIndex - MAX_INPUTS);
// Set the output so it can be exited later.
inFlightExit.outputs[_outputIndex - MAX_INPUTS] = output;
}
require(output.owner == msg.sender);
// Enqueue the exit in a right queue, if not already enqueued.
if (_shouldEnqueueInFlightExit(inFlightExit, output.token)) {
_enqueueExit(output.token, inFlightExit.exitPriority);
}
// Set the output as piggybacked.
setPiggybacked(inFlightExit, _outputIndex);
emit InFlightExitPiggybacked(msg.sender, txhash, _outputIndex);
}
function _shouldEnqueueInFlightExit(InFlightExit storage _inFlightExit, address _token)
internal
view
returns (bool)
{
for (uint8 i = 0; i < MAX_INPUTS; ++i) {
if (
(isPiggybacked(_inFlightExit, i) && _inFlightExit.inputs[i].token == _token)
||
(isPiggybacked(_inFlightExit, i + MAX_INPUTS) && _inFlightExit.outputs[i].token == _token)
) {
return false;
}
}
return true;
}
/**
* @dev Attempts to prove that an in-flight exit is not canonical.
* @param _inFlightTx RLP encoded in-flight transaction being exited.
* @param _inFlightTxInputIndex Index of the double-spent input in the in-flight transaction.
* @param _competingTx RLP encoded transaction that spent the input.
* @param _competingTxInputIndex Index of the double-spent input in the competing transaction.
* @param _competingTxPos Position of the competing transaction.
* @param _competingTxInclusionProof Proof that the competing transaction was included.
* @param _competingTxSig Signature proving that the owner of the input signed the competitor.
*/
function challengeInFlightExitNotCanonical(
bytes _inFlightTx,
uint8 _inFlightTxInputIndex,
bytes _competingTx,
uint8 _competingTxInputIndex,
uint256 _competingTxPos,
bytes _competingTxInclusionProof,
bytes _competingTxSig
)
public
{
// Check that the exit is active and in period 1.
InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx);
require(_firstPhaseNotOver(inFlightExit));
// Check if exit's input was spent via MVP exit
require(!isInputSpent(inFlightExit));
// Check that the two transactions are not the same.
require(keccak256(_inFlightTx) != keccak256(_competingTx));
// Check that the two transactions share an input.
uint256 inFlightTxInputPos = _inFlightTx.getInputUtxoPosition(_inFlightTxInputIndex);
require(inFlightTxInputPos == _competingTx.getInputUtxoPosition(_competingTxInputIndex));
// Check that the competing transaction is correctly signed.
PlasmaCore.TransactionOutput memory input = inFlightExit.inputs[_inFlightTxInputIndex];
require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_competingTx), _competingTxSig));
// Determine the position of the competing transaction.
uint256 competitorPosition = ~uint256(0);
if (_competingTxPos != 0) {
// Check that the competing transaction was included in a block.
require(_transactionIncluded(_competingTx, _competingTxPos, _competingTxInclusionProof));
competitorPosition = _competingTxPos;
}
// Competitor must be first or must be older than the current oldest competitor.
require(inFlightExit.oldestCompetitor == 0 || inFlightExit.oldestCompetitor > competitorPosition);
// Set the oldest competitor and new bond owner.
inFlightExit.oldestCompetitor = competitorPosition;
inFlightExit.bondOwner = msg.sender;
// Set a flag so that only the inputs are exitable, unless a response is received.
setNonCanonicalChallenge(inFlightExit);
emit InFlightExitChallenged(msg.sender, keccak256(_inFlightTx), competitorPosition);
}
/**
* @dev Allows a user to respond to competitors to an in-flight exit by showing the transaction is included.
* @param _inFlightTx RLP encoded in-flight transaction being exited.
* @param _inFlightTxPos Position of the in-flight transaction in the chain.
* @param _inFlightTxInclusionProof Proof that the in-flight transaction is included before the competitor.
*/
function respondToNonCanonicalChallenge(
bytes _inFlightTx,
uint256 _inFlightTxPos,
bytes _inFlightTxInclusionProof
)
public
{
InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx);
// Check that there is a challenge and in-flight transaction is older than its competitors.
require(inFlightExit.oldestCompetitor > _inFlightTxPos);
// Check that the in-flight transaction was included.
require(_transactionIncluded(_inFlightTx, _inFlightTxPos, _inFlightTxInclusionProof));
// Fix the oldest competitor and new bond owner.
inFlightExit.oldestCompetitor = _inFlightTxPos;
inFlightExit.bondOwner = msg.sender;
// Reset the flag so only the outputs are exitable.
setCanonical(inFlightExit);
emit InFlightExitChallengeResponded(msg.sender, keccak256(_inFlightTx), _inFlightTxPos);
}
/**
* @dev Removes an input from list of exitable outputs in an in-flight transaction.
* @param _inFlightTx RLP encoded in-flight transaction being exited.
* @param _inFlightTxInputIndex Input that's been spent.
* @param _spendingTx RLP encoded transaction that spends the input.
* @param _spendingTxInputIndex Which input to the spending transaction spends the input.
* @param _spendingTxSig Signature that shows the input owner signed the spending transaction.
*/
function challengeInFlightExitInputSpent(
bytes _inFlightTx,
uint8 _inFlightTxInputIndex,
bytes _spendingTx,
uint8 _spendingTxInputIndex,
bytes _spendingTxSig
)
public
{
InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx);
// Check that the input is piggybacked.
require(isPiggybacked(inFlightExit, _inFlightTxInputIndex));
// Check that the two transactions are not the same.
require(keccak256(_inFlightTx) != keccak256(_spendingTx));
// Check that the two transactions share an input.
uint256 inFlightTxInputPos = _inFlightTx.getInputUtxoPosition(_inFlightTxInputIndex);
require(inFlightTxInputPos == _spendingTx.getInputUtxoPosition(_spendingTxInputIndex));
// Check that the spending transaction is signed by the input owner.
PlasmaCore.TransactionOutput memory input = inFlightExit.inputs[_inFlightTxInputIndex];
require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_spendingTx), _spendingTxSig));
// Remove the input from the piggyback map and pay out the bond.
setExitCancelled(inFlightExit, _inFlightTxInputIndex);
msg.sender.transfer(piggybackBond);
emit InFlightExitOutputBlocked(msg.sender, keccak256(_inFlightTx), _inFlightTxInputIndex);
}
/**
* @dev Removes an output from list of exitable outputs in an in-flight transaction.
* @param _inFlightTx RLP encoded in-flight transaction being exited.
* @param _inFlightTxOutputPos Output that's been spent.
* @param _inFlightTxInclusionProof Proof that the in-flight transaction was included.
* @param _spendingTx RLP encoded transaction that spends the input.
* @param _spendingTxInputIndex Which input to the spending transaction spends the input.
* @param _spendingTxSig Signature that shows the input owner signed the spending transaction.
*/
function challengeInFlightExitOutputSpent(
bytes _inFlightTx,
uint256 _inFlightTxOutputPos,
bytes _inFlightTxInclusionProof,
bytes _spendingTx,
uint8 _spendingTxInputIndex,
bytes _spendingTxSig
)
public
{
InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx);
// Check that the output is piggybacked.
uint8 oindex = _inFlightTxOutputPos.getOindex();
require(isPiggybacked(inFlightExit, oindex + MAX_INPUTS));
// Check that the in-flight transaction is included.
require(_transactionIncluded(_inFlightTx, _inFlightTxOutputPos, _inFlightTxInclusionProof));
// Check that the spending transaction spends the output.
require(_inFlightTxOutputPos == _spendingTx.getInputUtxoPosition(_spendingTxInputIndex));
// Check that the spending transaction is signed by the input owner.
PlasmaCore.TransactionOutput memory output = _inFlightTx.getOutput(oindex);
require(output.owner == ECRecovery.recover(Eip712StructHash.hash(_spendingTx), _spendingTxSig));
// Remove the output from the piggyback map and pay out the bond.
setExitCancelled(inFlightExit, oindex + MAX_INPUTS);
msg.sender.transfer(piggybackBond);
emit InFlightExitOutputBlocked(msg.sender, keccak256(_inFlightTx), oindex);
}
/**
* @dev Processes any exits that have completed the challenge period.
* @param _token Token type to process.
* @param _topExitId First exit that should be processed. Set to zero to skip the check.
* @param _exitsToProcess Maximal number of exits to process.
*/
function processExits(address _token, uint192 _topExitId, uint256 _exitsToProcess)
public
{
uint64 exitableTimestamp;
uint192 exitId;
bool inFlight;
(exitableTimestamp, exitId, inFlight) = getNextExit(_token);
require(_topExitId == exitId || _topExitId == 0);
PriorityQueue queue = PriorityQueue(exitsQueues[_token]);
while (exitableTimestamp < block.timestamp && _exitsToProcess > 0) {
// Delete the minimum from the queue.
queue.delMin();
// Check for the in-flight exit flag.
if (inFlight) {
// handle ERC20 transfers for InFlight exits
_processInFlightExit(inFlightExits[exitId], exitId, _token);
// think of useful event scheme for in-flight outputs finalization
} else {
_processStandardExit(exits[exitId], exitId);
}
// Pull the next exit.
if (queue.currentSize() > 0) {
(exitableTimestamp, exitId, inFlight) = getNextExit(_token);
_exitsToProcess--;
} else {
return;
}
}
}
/**
* @dev Given an RLP encoded transaction, returns its exit ID.
* @param _tx RLP encoded transaction.
* @return _uniqueId A unique identifier of an in-flight exit.
* Anatomy of returned value, most significant bits first:
* 8 bits - set to zero
* 1 bit - in-flight flag
* 151 bit - tx hash
*/
function getInFlightExitId(bytes _tx)
public
pure
returns (uint192)
{
return uint192((uint256(keccak256(_tx)) >> 105).setBit(151));
}
/**
* @dev Given transaction bytes and UTXO position, returns its exit ID.
* @notice Id from a deposit is computed differently from any other tx.
* @param _txbytes Transaction bytes.
* @param _utxoPos UTXO position of the exiting output.
* @return _standardExitId Unique standard exit id.
* Anatomy of returned value, most significant bits first:
* 8 bits - oindex
* 1 bit - in-flight flag
* 151 bit - tx hash
*/
function getStandardExitId(bytes memory _txbytes, uint256 _utxoPos)
public
view
returns (uint192)
{
bytes memory toBeHashed = _txbytes;
if (_isDeposit(_utxoPos.getBlknum())){
toBeHashed = abi.encodePacked(_txbytes, _utxoPos);
}
return _computeStandardExitId(keccak256(toBeHashed), _utxoPos.getOindex());
}
function getFeeExitId(uint256 feeExitNum)
public
pure
returns (uint192)
{
return _computeStandardExitId(keccak256(feeExitNum), 0);
}
function _computeStandardExitId(bytes32 _txhash, uint8 _oindex)
internal
pure
returns (uint192)
{
return uint192((uint256(_txhash) >> 105) | (uint256(_oindex) << 152));
}
/**
* @dev Returns the next exit to be processed
* @return A tuple with timestamp for when the next exit is processable, its unique exit id
and flag determining if exit is in-flight one.
*/
function getNextExit(address _token)
public
view
returns (uint64, uint192, bool)
{
PriorityQueue queue = PriorityQueue(exitsQueues[_token]);
uint256 priority = queue.getMin();
return unpackExitId(priority);
}
function unpackExitId(uint256 priority)
public
pure
returns (uint64, uint192, bool)
{
uint64 exitableTimestamp = uint64(priority >> 214);
bool inFlight = priority.getBit(151) == 1;
// get 160 least significant bits
uint192 exitId = uint192((priority << 96) >> 96);
return (exitableTimestamp, exitId, inFlight);
}
/**
* @dev Checks if queue for particular token was created.
* @param _token Address of the token.
*/
function hasToken(address _token)
view
public
returns (bool)
{
return exitsQueues[_token] != address(0);
}
/**
* @dev Returns the data associated with an input or output to an in-flight transaction.
* @param _tx RLP encoded in-flight transaction.
* @param _outputIndex Index of the output to query.
* @return A tuple containing the output's owner and amount.
*/
function getInFlightExitOutput(bytes _tx, uint256 _outputIndex)
public
view
returns (address, address, uint256)
{
InFlightExit memory inFlightExit = _getInFlightExit(_tx);
PlasmaCore.TransactionOutput memory output;
if (_outputIndex < MAX_INPUTS) {
output = inFlightExit.inputs[_outputIndex];
} else {
output = inFlightExit.outputs[_outputIndex - MAX_INPUTS];
}
return (output.owner, output.token, output.amount);
}
/**
* @dev Calculates the next deposit block.
* @return Next deposit block number.
*/
function getDepositBlockNumber()
public
view
returns (uint256)
{
return nextChildBlock - CHILD_BLOCK_INTERVAL + nextDepositBlock;
}
function flagged(uint256 _value)
public
pure
returns (bool)
{
return _value.bitSet(255) || _value.bitSet(254);
}
/*
* Internal functions
*/
function getInFlightExitTimestamp(InFlightExit storage _ife)
private
view
returns (uint256)
{
return _ife.exitStartTimestamp.clearBit(255);
}
function isPiggybacked(InFlightExit storage _ife, uint8 _output)
view
private
returns (bool)
{
return _ife.exitMap.bitSet(_output);
}
function isExited(InFlightExit storage _ife, uint8 _output)
view
private
returns (bool)
{
return _ife.exitMap.bitSet(_output + MAX_INPUTS * 2);
}
function isInputSpent(InFlightExit storage _ife)
view
private
returns (bool)
{
return _ife.exitStartTimestamp.bitSet(254);
}
function setPiggybacked(InFlightExit storage _ife, uint8 _output)
private
{
_ife.exitMap = _ife.exitMap.setBit(_output);
}
function setExited(InFlightExit storage _ife, uint8 _output)
private
{
_ife.exitMap = _ife.exitMap.clearBit(_output).setBit(_output + 2 * MAX_INPUTS);
}
function setNonCanonical(InFlightExit storage _ife)
private
{
_ife.exitStartTimestamp = _ife.exitStartTimestamp.setBit(254);
}
function setFinalized(InFlightExit storage _ife)
private
{
_ife.exitMap = _ife.exitMap.setBit(255);
}
function setNonCanonicalChallenge(InFlightExit storage _ife)
private
{
_ife.exitStartTimestamp = _ife.exitStartTimestamp.setBit(255);
}
function setCanonical(InFlightExit storage _ife)
private
{
_ife.exitStartTimestamp = _ife.exitStartTimestamp.clearBit(255);
}
function setExitCancelled(InFlightExit storage _ife, uint8 _output)
private
{
_ife.exitMap = _ife.exitMap.clearBit(_output);
}
function isInputExit(InFlightExit storage _ife)
view
private
returns (bool)
{
return _ife.exitStartTimestamp.bitSet(255) || _ife.exitStartTimestamp.bitSet(254);
}
function isFinalized(InFlightExit storage _ife)
view
private
returns (bool)
{
return _ife.exitMap.bitSet(255);
}
/**
* @dev Given an utxo position, determines when it's exitable, if it were to be exited now.
* @param _utxoPos Output identifier.
* @return uint256 Timestamp after which this output is exitable.
*/
function getExitableTimestamp(uint256 _utxoPos)
public
view
returns (uint256)
{
uint256 blknum = _utxoPos.getBlknum();
if (_isDeposit(blknum)) {
// High priority exit for the deposit.
return block.timestamp + minExitPeriod;
}
else {
return Math.max(blocks[blknum].timestamp + (minExitPeriod * 2), block.timestamp + minExitPeriod);
}
}
/**
* @dev Given a fee exit ID returns an exit priority.
* @param _feeExitId Fee exit identifier.
* @return An exit priority.
*/
function getFeeExitPriority(uint192 _feeExitId)
public
view
returns (uint256)
{
return (uint256(block.timestamp + (minExitPeriod * 2)) << 214) | uint256(_feeExitId);
}
/**
* @dev Given a utxo position and a unique ID, returns an exit priority.
* @param _exitId Unique exit identifier.
* @param _utxoPos Position of the exit in the blockchain.
* @return An exit priority.
* Anatomy of returned value, most significant bits first
* 42 bits - timestamp (exitable_at); unix timestamp fits into 32 bits
* 54 bits - blknum * 10^9 + txindex; to represent all utxo for 10 years we need only 54 bits
* 8 bits - oindex; set to zero for in-flight tx
* 1 bit - in-flight flag
* 151 bit - tx hash
*/
function getStandardExitPriority(uint192 _exitId, uint256 _utxoPos)
public
view
returns (uint256)
{
uint256 tx_pos = _utxoPos.getTxPos();
return ((getExitableTimestamp(_utxoPos) << 214) | (tx_pos << 160)) | _exitId;
}
/**
* @dev Given a transaction and the ID for a output in the transaction, returns an exit priority.
* @param _txoPos Identifier of an output in the transaction.
* @param _tx RLP encoded transaction.
* @return An exit priority.
*/
function getInFlightExitPriority(bytes _tx, uint256 _txoPos)
view
returns (uint256)
{
return getStandardExitPriority(getInFlightExitId(_tx), _txoPos);
}
/**
* @dev Checks that a given transaction was included in a block and created a specified output.
* @param _tx RLP encoded transaction to verify.
* @param _transactionPos Transaction position for the encoded transaction.
* @param _txInclusionProof Proof that the transaction was in a block.
* @return True if the transaction was in a block and created the output. False otherwise.
*/
function _transactionIncluded(bytes _tx, uint256 _transactionPos, bytes _txInclusionProof)
internal
view
returns (bool)
{
// Decode the transaction ID.
uint256 blknum = _transactionPos.getBlknum();
uint256 txindex = _transactionPos.getTxIndex();
// Check that the transaction was correctly included.
bytes32 blockRoot = blocks[blknum].root;
bytes32 leafHash = keccak256(_tx);
return Merkle.checkMembership(leafHash, txindex, blockRoot, _txInclusionProof);
}
/**
* @dev Returns the in-flight exit for a given in-flight transaction.
* @param _inFlightTx RLP encoded in-flight transaction.
* @return An InFlightExit reference.
*/
function _getInFlightExit(bytes _inFlightTx)
internal
view
returns (InFlightExit storage)
{
return inFlightExits[getInFlightExitId(_inFlightTx)];
}
/**
* @dev Checks that in-flight exit is in phase that allows for piggybacks and canonicity challenges.
* @param _inFlightExit Exit to check.
* @return True only if in-flight exit is in phase that allows for piggybacks and canonicity challenges.
*/
function _firstPhaseNotOver(InFlightExit storage _inFlightExit)
internal
view
returns (bool)
{
uint256 periodTime = minExitPeriod / 2;
return ((block.timestamp - getInFlightExitTimestamp(_inFlightExit)) / periodTime) < 1;
}
/**
* @dev Returns the number of required inputs and sum of the outputs for a transaction.
* @param _tx RLP encoded transaction.
* @return A tuple containing the number of inputs and the sum of the outputs of tx.
*/
function _validateInputsOutputsSumUp(InFlightExit storage _inFlightExit, bytes _tx)
internal
view
{
_InputSum[MAX_INPUTS] memory sums;
uint8 allocatedSums = 0;
_InputSum memory tokenSum;
uint8 i;
// Loop through each input
for (i = 0; i < MAX_INPUTS; ++i) {
PlasmaCore.TransactionOutput memory input = _inFlightExit.inputs[i];
// Add current input amount to the overall transaction sum (token-wise)
(tokenSum, allocatedSums) = _getInputSumByToken(sums, allocatedSums, input.token);
tokenSum.amount += input.amount;
}
// Loop through each output
for (i = 0; i < MAX_INPUTS; ++i) {
PlasmaCore.TransactionOutput memory output = _tx.getOutput(i);
(tokenSum, allocatedSums) = _getInputSumByToken(sums, allocatedSums, output.token);
// Underflow protection
require(tokenSum.amount >= output.amount);
tokenSum.amount -= output.amount;
}
}
/**
* @dev Returns element of an array where sum of the given token is stored.
* @param _sums array of sums by tokens
* @param _allocated Number of currently allocated elements in _sums array
* @param _token Token address which sum is being searched for
* @return A tuple containing element of array and an updated number of currently allocated elements
*/
function _getInputSumByToken(_InputSum[MAX_INPUTS] memory _sums, uint8 _allocated, address _token)
internal
pure
returns (_InputSum, uint8)
{
// Find token sum within already used ones
for (uint8 i = 0; i < _allocated; ++i) {
if (_sums[i].token == _token) {
return (_sums[i], _allocated);
}
}
// Check whether trying to allocate new token sum, even though all has been used
// Notice: that there will never be more tokens than number of inputs,
// as outputs must be of the same tokens as inputs
require(_allocated < MAX_INPUTS);
// Allocate new token sum
_sums[_allocated].token = _token;
return (_sums[_allocated], _allocated + 1);
}
/**
* @dev Returns information about an input to a in-flight transaction.
* @param _tx RLP encoded transaction.
* @param _inputTx RLP encoded transaction that created particular input to this transaction.
* @param _txInputTxsInclusionProofs Proofs of inclusion for each input creation transaction.
* @param _inputSig Signature for spent output of the input transaction.
* @param _inputIndex Which input to access.
* @return A tuple containing information about the inputs.
*/
function _getInputInfo(
bytes _tx,
bytes memory _inputTx,
bytes _txInputTxsInclusionProofs,
bytes _inputSig,
uint8 _inputIndex
)
internal
view
returns (PlasmaCore.TransactionOutput, uint256, bool)
{
bool already_finalized;
// Pull information about the the input.
uint256 inputUtxoPos = _tx.getInputUtxoPosition(_inputIndex);
PlasmaCore.TransactionOutput memory input = _inputTx.getOutput(inputUtxoPos.getOindex());
// Check that the transaction is valid.
require(_transactionIncluded(_inputTx, inputUtxoPos, _txInputTxsInclusionProofs.sliceProof(_inputIndex)));
require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_tx), _inputSig));
// Challenge exiting standard exits from inputs
already_finalized = _cleanupDoubleSpendingStandardExits(inputUtxoPos, _inputTx);
return (input, inputUtxoPos, already_finalized);
}
/**
* @dev Processes a standard exit.
* @param _standardExit Exit to process.
*/
function _processStandardExit(Exit storage _standardExit, uint192 exitId)
internal
{
// If the exit is valid, pay out the exit and refund the bond.
if (_standardExit.owner != address(0)) {
if (_standardExit.token == address(0)) {
_standardExit.owner.transfer(_standardExit.amount + standardExitBond);
}
else {
require(ERC20(_standardExit.token).transfer(_standardExit.owner, _standardExit.amount));
_standardExit.owner.transfer(standardExitBond);
}
// Only delete the owner so someone can't exit from the same output twice.
delete _standardExit.owner;
// Delete token too, since check is done by amount anyway.
delete _standardExit.token;
emit ExitFinalized(exitId);
}
}
/**
* @dev Processes an in-flight exit.
* @param _inFlightExit Exit to process.
* @param _inFlightExitId Id of the exit process
* @param _token Token from which exits are to be processed
*/
function _processInFlightExit(InFlightExit storage _inFlightExit, uint192 _inFlightExitId, address _token)
internal
{
// Determine whether the inputs or the outputs are the exitable set.
bool inputsExitable = isInputExit(_inFlightExit);
// Process the inputs or outputs.
PlasmaCore.TransactionOutput memory output;
uint256 ethTransferAmount;
for (uint8 i = 0; i < 8; i++) {
if (i < MAX_INPUTS) {
output = _inFlightExit.inputs[i];
} else {
output = _inFlightExit.outputs[i - MAX_INPUTS];
}
// Check if the output's token or the "to exit" bit is not set.
if (output.token != _token || !isPiggybacked(_inFlightExit, i)) {
continue;
}
// Set bit flag to prevent future exits by standard exit mechanism.
setExited(_inFlightExit, i);
// Pay out any unchallenged and exitable inputs or outputs, refund the rest.
ethTransferAmount = piggybackBond;
if ((i < MAX_INPUTS && inputsExitable) || (i >= MAX_INPUTS && !inputsExitable)) {
if (_token == address(0)) {
ethTransferAmount += output.amount;
}
else {
require(ERC20(_token).transfer(output.owner, output.amount));
}
emit InFlightExitFinalized(_inFlightExitId, i);
}
output.owner.transfer(ethTransferAmount);
}
if (_shouldClearInFlightExit(_inFlightExit)) {
_clearInFlightExit(_inFlightExit);
}
}
function _shouldClearInFlightExit(InFlightExit storage _inFlightExit)
internal
returns (bool)
{
for (uint8 i = 0; i < MAX_INPUTS * 2; ++i) {
// Check if any output is still piggybacked and awaits processing
if (isPiggybacked(_inFlightExit, i)) {
return false;
}
}
return true;
}
function _clearInFlightExit(InFlightExit storage _inFlightExit)
internal
{
// Refund the current bond owner.
_inFlightExit.bondOwner.transfer(inFlightExitBond);
// Flag as finalized
setFinalized(_inFlightExit);
// Delete everything but the exit map to block exits from already processed outputs.
delete _inFlightExit.exitStartTimestamp;
delete _inFlightExit.exitPriority;
delete _inFlightExit.inputs;
delete _inFlightExit.outputs;
delete _inFlightExit.bondOwner;
delete _inFlightExit.oldestCompetitor;
}
function _isDeposit(uint256 blknum)
internal
returns (bool)
{
return blknum % CHILD_BLOCK_INTERVAL != 0;
}
/**
* @dev Can be called only once in `init`.
*/
function _initOperator()
{
require(operator == address(0));
operator = msg.sender;
}
}
|
Removes an input from list of exitable outputs in an in-flight transaction. _inFlightTx RLP encoded in-flight transaction being exited. _inFlightTxInputIndex Input that's been spent. _spendingTx RLP encoded transaction that spends the input. _spendingTxInputIndex Which input to the spending transaction spends the input. _spendingTxSig Signature that shows the input owner signed the spending transaction./ Check that the input is piggybacked. Check that the two transactions are not the same. Check that the two transactions share an input. Check that the spending transaction is signed by the input owner. Remove the input from the piggyback map and pay out the bond.
|
function challengeInFlightExitInputSpent(
bytes _inFlightTx,
uint8 _inFlightTxInputIndex,
bytes _spendingTx,
uint8 _spendingTxInputIndex,
bytes _spendingTxSig
)
public
{
InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx);
require(isPiggybacked(inFlightExit, _inFlightTxInputIndex));
require(keccak256(_inFlightTx) != keccak256(_spendingTx));
uint256 inFlightTxInputPos = _inFlightTx.getInputUtxoPosition(_inFlightTxInputIndex);
require(inFlightTxInputPos == _spendingTx.getInputUtxoPosition(_spendingTxInputIndex));
PlasmaCore.TransactionOutput memory input = inFlightExit.inputs[_inFlightTxInputIndex];
require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_spendingTx), _spendingTxSig));
setExitCancelled(inFlightExit, _inFlightTxInputIndex);
msg.sender.transfer(piggybackBond);
emit InFlightExitOutputBlocked(msg.sender, keccak256(_inFlightTx), _inFlightTxInputIndex);
}
| 6,432,305 |
pragma solidity ^0.4.24;
// File: contracts/PeriodUtil.sol
/**
* @title PeriodUtil
*
* Interface used for Period calculation to allow better automated testing of Fees Contract
*
* (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence.
*/
contract PeriodUtil {
/**
* @dev calculates the Period index for the given timestamp
* @return Period count since EPOCH
* @param timestamp The time in seconds since EPOCH (blocktime)
*/
function getPeriodIdx(uint256 timestamp) public pure returns (uint256);
/**
* @dev Timestamp of the period start
* @return Time in seconds since EPOCH of the Period Start
* @param periodIdx Period Index to find the start timestamp of
*/
function getPeriodStartTimestamp(uint256 periodIdx) public pure returns (uint256);
/**
* @dev Returns the Cycle count of the given Periods. A set of time creates a cycle, eg. If period is weeks the cycle can be years.
* @return The Cycle Index
* @param timestamp The time in seconds since EPOCH (blocktime)
*/
function getPeriodCycle(uint256 timestamp) public pure returns (uint256);
/**
* @dev Amount of Tokens per time unit since the start of the given periodIdx
* @return Tokens per Time Unit from the given periodIdx start till now
* @param tokens Total amount of tokens from periodIdx start till now (blocktime)
* @param periodIdx Period IDX to use for time start
*/
function getRatePerTimeUnits(uint256 tokens, uint256 periodIdx) public view returns (uint256);
/**
* @dev Amount of time units in each Period, for exampe if units is hour and period is week it will be 168
* @return Amount of time units per period
*/
function getUnitsPerPeriod() public pure returns (uint256);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts/ERC20Burnable.sol
/**
* @title BurnableToken
*
* Interface for Basic ERC20 interactions and allowing burning of tokens
*
* (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence.
*/
contract ERC20Burnable is ERC20Basic {
function burn(uint256 _value) public;
}
// File: openzeppelin-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) {
// 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;
}
}
// File: contracts/ZCFees.sol
/**
* @title ZCFees
*
* Used to process transaction
*
* (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence.
*/
contract ZCFees {
using SafeMath for uint256;
struct PaymentHistory {
// If set
bool paid;
// Payment to Fees
uint256 fees;
// Payment to Reward
uint256 reward;
// End of period token balance
uint256 endBalance;
}
mapping (uint256 => PaymentHistory) payments;
address public tokenAddress;
PeriodUtil public periodUtil;
// Last week that has been executed
uint256 public lastPeriodExecIdx;
// Last Year that has been processed
uint256 public lastPeriodCycleExecIdx;
// Amount of time in seconds grase processing time
uint256 grasePeriod;
// Wallet for Fees payments
address public feesWallet;
// Wallet for Reward payments
address public rewardWallet;
// Fees 1 : % tokens taken per week
uint256 internal constant FEES1_PER = 10;
// Fees 1 : Max token payout per week
uint256 internal constant FEES1_MAX_AMOUNT = 400000 * (10**18);
// Fees 2 : % tokens taken per week
uint256 internal constant FEES2_PER = 10;
// Fees 2 : Max token payout per week
uint256 internal constant FEES2_MAX_AMOUNT = 800000 * (10**18);
// Min Amount of Fees to pay out per week
uint256 internal constant FEES_TOKEN_MIN_AMOUNT = 24000 * (10**18);
// Min Percentage Prev Week to pay out per week
uint256 internal constant FEES_TOKEN_MIN_PERPREV = 95;
// Rewards Percentage of Period Received
uint256 internal constant REWARD_PER = 70;
// % Amount of remaining tokens to burn at end of year
uint256 internal constant BURN_PER = 25;
/**
* @param _tokenAdr The Address of the Token
* @param _periodUtilAdr The Address of the PeriodUtil
* @param _grasePeriod The time in seconds you allowed to process payments before avg is calculated into next period(s)
* @param _feesWallet Where the fees are sent in tokens
* @param _rewardWallet Where the rewards are sent in tokens
*/
constructor (address _tokenAdr, address _periodUtilAdr, uint256 _grasePeriod, address _feesWallet, address _rewardWallet) public {
assert(_tokenAdr != address(0));
assert(_feesWallet != address(0));
assert(_rewardWallet != address(0));
assert(_periodUtilAdr != address(0));
tokenAddress = _tokenAdr;
feesWallet = _feesWallet;
rewardWallet = _rewardWallet;
periodUtil = PeriodUtil(_periodUtilAdr);
grasePeriod = _grasePeriod;
assert(grasePeriod > 0);
// GrasePeriod must be less than period
uint256 va1 = periodUtil.getPeriodStartTimestamp(1);
uint256 va2 = periodUtil.getPeriodStartTimestamp(0);
assert(grasePeriod < (va1 - va2));
// Set the previous period values;
lastPeriodExecIdx = getWeekIdx() - 1;
lastPeriodCycleExecIdx = getYearIdx();
PaymentHistory storage prevPayment = payments[lastPeriodExecIdx];
prevPayment.fees = 0;
prevPayment.reward = 0;
prevPayment.paid = true;
prevPayment.endBalance = 0;
}
/**
* @dev Call when Fees processing needs to happen. Can only be called by the contract Owner
*/
function process() public {
uint256 currPeriodIdx = getWeekIdx();
// Has the previous period been calculated?
if (lastPeriodExecIdx == (currPeriodIdx - 1)) {
// Nothing to do previous week has Already been processed
return;
}
if ((currPeriodIdx - lastPeriodExecIdx) == 2) {
paymentOnTime(currPeriodIdx);
// End Of Year Payment
if (lastPeriodCycleExecIdx < getYearIdx()) {
processEndOfYear(currPeriodIdx - 1);
}
}
else {
uint256 availableTokens = currentBalance();
// Missed Full Period! Very Bad!
PaymentHistory memory lastExecPeriod = payments[lastPeriodExecIdx];
uint256 tokensReceived = availableTokens.sub(lastExecPeriod.endBalance);
// Average amount of tokens received per hour till now
uint256 tokenHourlyRate = periodUtil.getRatePerTimeUnits(tokensReceived, lastPeriodExecIdx + 1);
PaymentHistory memory prePeriod;
for (uint256 calcPeriodIdx = lastPeriodExecIdx + 1; calcPeriodIdx < currPeriodIdx; calcPeriodIdx++) {
prePeriod = payments[calcPeriodIdx - 1];
uint256 periodTokenReceived = periodUtil.getUnitsPerPeriod().mul(tokenHourlyRate);
makePayments(prePeriod, payments[calcPeriodIdx], periodTokenReceived, prePeriod.endBalance.add(periodTokenReceived), calcPeriodIdx);
if (periodUtil.getPeriodCycle(periodUtil.getPeriodStartTimestamp(calcPeriodIdx + 1)) > lastPeriodCycleExecIdx) {
processEndOfYear(calcPeriodIdx);
}
}
}
assert(payments[currPeriodIdx - 1].paid);
lastPeriodExecIdx = currPeriodIdx - 1;
}
/**
* @dev Internal function to process end of year Clearance
* @param yearEndPeriodCycle The Last Period Idx (Week Idx) of the year
*/
function processEndOfYear(uint256 yearEndPeriodCycle) internal {
PaymentHistory storage lastYearPeriod = payments[yearEndPeriodCycle];
uint256 availableTokens = currentBalance();
uint256 tokensToClear = min256(availableTokens,lastYearPeriod.endBalance);
// Burn some of tokens
uint256 tokensToBurn = tokensToClear.mul(BURN_PER).div(100);
ERC20Burnable(tokenAddress).burn(tokensToBurn);
assert(ERC20Burnable(tokenAddress).transfer(feesWallet, tokensToClear.sub(tokensToBurn)));
lastPeriodCycleExecIdx = lastPeriodCycleExecIdx + 1;
lastYearPeriod.endBalance = 0;
emit YearEndClearance(lastPeriodCycleExecIdx, tokensToClear);
}
/**
* @dev Called when Payments are call within a week of last payment
* @param currPeriodIdx Current Period Idx (Week)
*/
function paymentOnTime(uint256 currPeriodIdx) internal {
uint256 availableTokens = currentBalance();
PaymentHistory memory prePeriod = payments[currPeriodIdx - 2];
uint256 tokensRecvInPeriod = availableTokens.sub(prePeriod.endBalance);
if (tokensRecvInPeriod <= 0) {
tokensRecvInPeriod = 0;
}
else if ((now - periodUtil.getPeriodStartTimestamp(currPeriodIdx)) > grasePeriod) {
tokensRecvInPeriod = periodUtil.getRatePerTimeUnits(tokensRecvInPeriod, currPeriodIdx - 1).mul(periodUtil.getUnitsPerPeriod());
if (tokensRecvInPeriod <= 0) {
tokensRecvInPeriod = 0;
}
assert(availableTokens >= tokensRecvInPeriod);
}
makePayments(prePeriod, payments[currPeriodIdx - 1], tokensRecvInPeriod, prePeriod.endBalance + tokensRecvInPeriod, currPeriodIdx - 1);
}
/**
* @dev Process a payment period
* @param prevPayment Previous periods payment records
* @param currPayment Current periods payment records to be updated
* @param tokensRaised Tokens received for the period
* @param availableTokens Contract available balance including the tokens received for the period
*/
function makePayments(PaymentHistory memory prevPayment, PaymentHistory storage currPayment, uint256 tokensRaised, uint256 availableTokens, uint256 weekIdx) internal {
assert(prevPayment.paid);
assert(!currPayment.paid);
assert(availableTokens >= tokensRaised);
// Fees 1 Payment
uint256 fees1Pay = tokensRaised == 0 ? 0 : tokensRaised.mul(FEES1_PER).div(100);
if (fees1Pay >= FEES1_MAX_AMOUNT) {
fees1Pay = FEES1_MAX_AMOUNT;
}
// Fees 2 Payment
uint256 fees2Pay = tokensRaised == 0 ? 0 : tokensRaised.mul(FEES2_PER).div(100);
if (fees2Pay >= FEES2_MAX_AMOUNT) {
fees2Pay = FEES2_MAX_AMOUNT;
}
uint256 feesPay = fees1Pay.add(fees2Pay);
if (feesPay >= availableTokens) {
feesPay = availableTokens;
} else {
// Calculates the Min percentage of previous month to pay
uint256 prevFees95 = prevPayment.fees.mul(FEES_TOKEN_MIN_PERPREV).div(100);
// Minimum amount of fees that is required
uint256 minFeesPay = max256(FEES_TOKEN_MIN_AMOUNT, prevFees95);
feesPay = max256(feesPay, minFeesPay);
feesPay = min256(feesPay, availableTokens);
}
// Rewards Payout
uint256 rewardPay = 0;
if (feesPay < tokensRaised) {
// There is money left for reward pool
rewardPay = tokensRaised.mul(REWARD_PER).div(100);
rewardPay = min256(rewardPay, availableTokens.sub(feesPay));
}
currPayment.fees = feesPay;
currPayment.reward = rewardPay;
assert(ERC20Burnable(tokenAddress).transfer(rewardWallet, rewardPay));
assert(ERC20Burnable(tokenAddress).transfer(feesWallet, feesPay));
currPayment.endBalance = availableTokens - feesPay - rewardPay;
currPayment.paid = true;
emit Payment(weekIdx, rewardPay, feesPay);
}
/**
* @dev Event when payment was made
* @param weekIdx Week Idx since EPOCH for payment
* @param rewardPay Amount of tokens paid to the reward pool
* @param feesPay Amount of tokens paid in fees
*/
event Payment(uint256 weekIdx, uint256 rewardPay, uint256 feesPay);
/**
* @dev Event when year end clearance happens
* @param yearIdx Year the clearance happend for
* @param feesPay Amount of tokens paid in fees
*/
event YearEndClearance(uint256 yearIdx, uint256 feesPay);
/**
* @dev Returns the token balance of the Fees contract
*/
function currentBalance() internal view returns (uint256) {
return ERC20Burnable(tokenAddress).balanceOf(address(this));
}
/**
* @dev Returns the amount of weeks since EPOCH
* @return Week count since EPOCH
*/
function getWeekIdx() public view returns (uint256) {
return periodUtil.getPeriodIdx(now);
}
/**
* @dev Returns the Year
*/
function getYearIdx() public view returns (uint256) {
return periodUtil.getPeriodCycle(now);
}
/**
* @dev Returns true if the week has been processed and paid out
* @param weekIdx Weeks since EPOCH
* @return true if week has been paid out
*/
function weekProcessed(uint256 weekIdx) public view returns (bool) {
return payments[weekIdx].paid;
}
/**
* @dev Returns the amounts paid out for the given week
* @param weekIdx Weeks since EPOCH
*/
function paymentForWeek(uint256 weekIdx) public view returns (uint256 fees, uint256 reward) {
PaymentHistory storage history = payments[weekIdx];
fees = history.fees;
reward = history.reward;
}
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;
}
}
|
Returns the amount of weeks since EPOCH return Week count since EPOCH/
|
function getWeekIdx() public view returns (uint256) {
return periodUtil.getPeriodIdx(now);
}
| 127,776 |
pragma solidity ^0.4.21;
import "openzeppelin-solidity/contracts/ownership/Claimable.sol";
import "../TimeLockedController.sol";
/*
Allows for admins to quickly respond to fradulent mints
After deploying FastPauseMints and configuring it with TimeLockedController
Can pause trueUSD by simply sending any amount of ether to this contract
from the trueUsdPauser address
*/
contract FastPauseMints is Claimable {
TimeLockedController public controllerContract;
event PauseKeyModified (address pauseKey, bool isValid);
event Pauser(address who);
mapping(address => bool) public isPauseKey;
modifier onlyPauseKey() {
require(isPauseKey[msg.sender], "not pause key");
_;
}
function setController(address _newContract) public onlyOwner {
controllerContract = TimeLockedController(_newContract);
}
//modify which addresses can pause mints by sending in eth
function modifyPauseKey(address _pauseKey, bool _isValid ) public onlyOwner {
isPauseKey[_pauseKey] = _isValid;
emit PauseKeyModified(_pauseKey, _isValid);
}
//fallback function used to pause mints when it recieves eth
function() public payable onlyPauseKey {
emit Pauser(msg.sender);
msg.sender.transfer(msg.value);
controllerContract.pauseMints();
}
}
|
fallback function used to pause mints when it recieves eth
|
function() public payable onlyPauseKey {
emit Pauser(msg.sender);
msg.sender.transfer(msg.value);
controllerContract.pauseMints();
}
| 7,307,607 |
./full_match/1/0x92344754a9060a52A634B3c6b8118f76baD1A448/sources/contracts/staking/AaveCall.sol
|
Get repay calldata from ETF Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address _lendingPool Address of the LendingPool contract _asset The address of the borrowed underlying asset previously borrowed _amountNotional The amount to repay Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode` _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable _onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the user calling the function if he wants to reduce/remove his own debt, or the address of any other other borrower whose debt should be removed return address Target contract address return uint256 Call value return bytes Repay calldata/
|
function getRepayCalldata(
ILendingPool _lendingPool,
address _asset,
uint256 _amountNotional,
uint256 _interestRateMode,
address _onBehalfOf
) internal pure returns (address, uint256, bytes memory) {
bytes memory callData = abi.encodeWithSignature(
'repay(address,uint256,uint256,address)',
_asset,
_amountNotional,
_interestRateMode,
_onBehalfOf
);
return (address(_lendingPool), 0, callData);
}
| 2,998,043 |
./full_match/1/0x668434279A7380E4Da683897BB02D8a77B6caE0A/sources/Users/shengdading/git/acSaving/contracts/strategies/StrategyBase.sol
|
Used to salvage any ETH deposited into the vault by mistake. Only governance or strategist can salvage ETH from the vault. The salvaged ETH is transferred to treasury for futher operation./
|
function salvage() public onlyStrategist {
uint256 amount = address(this).balance;
address payable target = payable(IController(controller()).treasury());
require(success, 'ETH salvage failed');
}
| 8,386,699 |
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol
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
);
}
// File: @chainlink/contracts/src/v0.8/dev/VRFRequestIDBase.sol
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));
}
}
// File: @chainlink/contracts/src/v0.8/dev/VRFConsumerBase.sol
pragma solidity ^0.8.0;
/** ****************************************************************************
* @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);
}
}
// File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: contracts/OwnershipAgreementv3.sol
pragma solidity >=0.7.0 <0.9.0;
/// @title Creates an Ownership Agreement, with an optional Operator role
/// @author Dr. Jonathan Shahen at UREEQA
/// @notice TODO
/// @dev Maximum number of Owners is set to 255 (unit8.MAX_VALUE)
contract OwnershipAgreementv3 {
/*
* Storage
*/
// ResolutionTypes:
uint constant private resTypeNone = 0; // This indicates that the resolution hasn't been set (default value)
uint constant private resTypeAddOwner = 1;
uint constant private resTypeRemoveOwner = 2;
uint constant private resTypeReplaceOwner = 3;
uint constant private resTypeAddOperator = 4;
uint constant private resTypeRemoveOperator = 5;
uint constant private resTypeReplaceOperator = 6;
uint constant private resTypeUpdateThreshold = 7;
uint constant private resTypeUpdateTransactionLimit = 8;
uint constant private resTypePause = 9;
uint constant private resTypeUnpause = 10;
uint constant private resTypeCustom = 1000; // Custom resoutions for each subclass
struct Resolution {
// Has the resolution already been passed
bool passed;
// The type of resolution
uint256 resType;
// The old address, can be address(0). oldAddress and newAddress cannot both equal address(0).
address oldAddress;
// The new address, can be address(0). oldAddress and newAddress cannot both equal address(0).
address newAddress;
// Able to store extra information for custom resolutions
bytes32[] extra;
}
using EnumerableSet for EnumerableSet.AddressSet;
// Set of owners
// NOTE: we utilize a set, so we can enumerate the owners and so that the list only contains one instance of an account
// NOTE: address(0) is not a valid owner
EnumerableSet.AddressSet private _owners;
// Value to indicate if the smart contract is paused
bool private _paused;
// An address, usually controlled by a computer, that performs regular/automated operations within the smart contract
// NOTE: address(0) is not a valid operator
EnumerableSet.AddressSet private _operators;
// Limit the number of operators
uint256 public operatorLimit = 1;
// The number of owners it takes to come to an agreement
uint256 public ownerAgreementThreshold = 1;
// Limit per Transaction to impose
// A limit of zero means no limit imposed
uint256 public transactionLimit = 0;
// Stores each vote for each resolution number (int)
mapping(address => mapping(uint256 => bool)) public ownerVotes;
// The next available resolution number
uint256 public nextResolution = 1;
mapping(address => uint256) lastOwnerResolutionNumber;
// Stores the resolutions
mapping(uint256 => Resolution) public resolutions;
// ////////////////////////////////////////////////////
// EVENTS
// ////////////////////////////////////////////////////
event OwnerAddition(address owner);
event OwnerRemoval(address owner);
event OwnerReplacement(address oldOwner, address newOwner);
event OperatorAddition(address newOperator);
event OperatorRemoval(address oldOperator);
event OperatorReplacement(address oldOperator, address newOperator);
event UpdateThreshold(uint256 newThreshold);
event UpdateNumberOfOperators(uint256 newOperators);
event UpdateTransactionLimit(uint256 newLimit);
/// @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);
// ////////////////////////////////////////////////////
// MODIFIERS
// ////////////////////////////////////////////////////
function isValidAddress(address newAddr) public pure {
require(newAddr != address(0), "Invaild Address");
}
modifier onlyOperators() {
isValidAddress(msg.sender);
require(
EnumerableSet.contains(_operators, msg.sender) == true,
"Only the operator can run this function."
);
_;
}
modifier onlyOwners() {
isValidAddress(msg.sender);
require(
EnumerableSet.contains(_owners, msg.sender) == true,
"Only an owner can run this function."
);
_;
}
modifier onlyOwnersOrOperator() {
isValidAddress(msg.sender);
require(
EnumerableSet.contains(_operators, msg.sender) == true ||
EnumerableSet.contains(_owners, msg.sender) == true,
"Only an owner or the operator can run this function."
);
_;
}
modifier ownerExists(address thisOwner) {
require(
EnumerableSet.contains(_owners, thisOwner) == true,
"Owner does not exists."
);
_;
}
/**
* @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, "Smart Contract is paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
* Requirements: The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Smart Contract is not paused");
_;
}
/// @dev Modifier to make a function callable only when the amount is within the transaction limit
modifier withinLimit(uint256 amount) {
require(
transactionLimit == 0 || amount <= transactionLimit,
"Amount is over the transaction limit"
);
_;
}
// ////////////////////////////////////////////////////
// CONSTRUCTOR
// ////////////////////////////////////////////////////
constructor() {
_addOwner(msg.sender);
_paused = false;
}
// ////////////////////////////////////////////////////
// VIEW FUNCTIONS
// ////////////////////////////////////////////////////
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
if(EnumerableSet.length(_owners) == 0) return address(0);
return EnumerableSet.at(_owners, 0);
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
uint256 len = EnumerableSet.length(_owners);
address[] memory o = new address[](len);
for (uint256 i = 0; i < len; i++) {
o[i] = EnumerableSet.at(_owners, i);
}
return o;
}
/// @dev Returns the number of owners.
/// @return Number of owners.
function getNumberOfOwners() public view returns (uint) {
return EnumerableSet.length(_owners);
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOperators() public view returns (address[] memory) {
uint256 len = EnumerableSet.length(_operators);
address[] memory o = new address[](len);
for (uint256 i = 0; i < len; i++) {
o[i] = EnumerableSet.at(_operators, i);
}
return o;
}
/// @dev Returns the number of operators.
/// @return Number of operators.
function getNumberOfOperators() public view returns (uint8) {
return uint8(EnumerableSet.length(_operators));
}
/// @dev How many owners does it take to approve a resolution
/// @return minimum number of owner votes
function getVoteThreshold() public view returns (uint256) {
return ownerAgreementThreshold;
}
/// @dev Returns the maximum amount a transaction can contain
/// @return maximum amount or zero is no limit
function getTransactionLimit() public view returns (uint256) {
return transactionLimit;
}
/// @dev Returns the next available resolution.
/// @return The next available resolution number
function getNextResolutionNumber() public view returns (uint256) {
return nextResolution;
}
/// @dev Returns the next available resolution.
/// @return The next available resolution number
function getLastOwnerResolutionNumber(address thisOwner)
public
view
returns (uint256)
{
return lastOwnerResolutionNumber[thisOwner];
}
/// @dev Returns true if the contract is paused, and false otherwise.
function paused() public view returns (bool) {
return _paused;
}
/// @dev Helper function to fail if resolution number is already in use.
function resolutionAlreadyUsed(uint256 resNum) public view {
require(
// atleast one of the address must not be equal to address(0)
!(resolutions[resNum].oldAddress != address(0) ||
resolutions[resNum].newAddress != address(0)),
"Resolution is already in use."
);
}
function isResolutionPassed(uint256 resNum) public view returns (bool) {
return resolutions[resNum].passed;
}
function canResolutionPass(uint256 resNum) public view returns (bool) {
uint256 voteCount = 0;
uint256 len = EnumerableSet.length(_owners);
for (uint256 i = 0; i < len; i++) {
if (ownerVotes[EnumerableSet.at(_owners, i)][resNum] == true) {
voteCount++;
}
}
return voteCount >= ownerAgreementThreshold;
}
// ////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
// ////////////////////////////////////////////////////
/// @notice Vote Yes on a Resolution.
/// @dev The owner who tips the agreement threshold will pay the gas for performing the resolution.
/// @return TRUE if the resolution passed
function voteResolution(uint256 resNum) public onlyOwners() returns (bool) {
ownerVotes[msg.sender][resNum] = true;
// If the reolution has already passed, then do nothing
if (isResolutionPassed(resNum)) {
return true;
}
// If the resolution can now be passed, then do so
if (canResolutionPass(resNum)) {
_performResolution(resNum);
return true;
}
// The resolution cannot be passed yet
return false;
}
/// @dev Create a resolution to add an owner. Performs addition if threshold is 1 or zero.
function createResolutionAddOwner(address newOwner) public onlyOwners() {
isValidAddress(newOwner);
require(
!EnumerableSet.contains(_owners, newOwner),
"newOwner already exists."
);
createResolution(resTypeAddOwner, address(0), newOwner, new bytes32[](0));
}
/// @dev Create a resolution to remove an owner. Performs removal if threshold is 1 or zero.
/// @dev Updates the threshold to keep it less than or equal to the number of new owners
function createResolutionRemoveOwner(address oldOwner) public onlyOwners() {
isValidAddress(oldOwner);
require(getNumberOfOwners() > 1, "Must always be one owner");
require(
EnumerableSet.contains(_owners, oldOwner),
"owner is not an owner."
);
createResolution(resTypeRemoveOwner, oldOwner, address(0), new bytes32[](0));
}
/// @dev Create a resolution to repalce an owner. Performs replacement if threshold is 1 or zero.
function createResolutionReplaceOwner(address oldOwner, address newOwner)
public
onlyOwners()
{
isValidAddress(oldOwner);
isValidAddress(newOwner);
require(
EnumerableSet.contains(_owners, oldOwner),
"oldOwner is not an owner."
);
require(
!EnumerableSet.contains(_owners, newOwner),
"newOwner already exists."
);
createResolution(resTypeReplaceOwner, oldOwner, newOwner, new bytes32[](0));
}
/// @dev Create a resolution to add an operator. Performs addition if threshold is 1 or zero.
function createResolutionAddOperator(address newOperator)
public
onlyOwners()
{
isValidAddress(newOperator);
require(
!EnumerableSet.contains(_operators, newOperator),
"newOperator already exists."
);
createResolution(resTypeAddOperator, address(0), newOperator, new bytes32[](0));
}
/// @dev Create a resolution to remove the operator. Performs removal if threshold is 1 or zero.
function createResolutionRemoveOperator(address operator)
public
onlyOwners()
{
require(
EnumerableSet.contains(_operators, operator),
"operator is not an Operator."
);
createResolution(resTypeRemoveOperator, operator, address(0), new bytes32[](0));
}
/// @dev Create a resolution to replace the operator account. Performs replacement if threshold is 1 or zero.
function createResolutionReplaceOperator(
address oldOperator,
address newOperator
) public onlyOwners() {
isValidAddress(oldOperator);
isValidAddress(newOperator);
require(
EnumerableSet.contains(_operators, oldOperator),
"oldOperator is not an Operator."
);
require(
!EnumerableSet.contains(_operators, newOperator),
"newOperator already exists."
);
createResolution(resTypeReplaceOperator, oldOperator, newOperator,new bytes32[](0));
}
/// @dev Create a resolution to update the transaction limit. Performs update if threshold is 1 or zero.
function createResolutionUpdateTransactionLimit(uint160 newLimit)
public
onlyOwners()
{
createResolution(
resTypeUpdateTransactionLimit,
address(0),
address(newLimit),
new bytes32[](0)
);
}
/// @dev Create a resolution to update the owner agreement threshold. Performs update if threshold is 1 or zero.
function createResolutionUpdateThreshold(uint160 threshold)
public
onlyOwners()
{
createResolution(
resTypeUpdateThreshold,
address(0),
address(threshold),
new bytes32[](0)
);
}
/// @dev Pause the contract. Does not require owner agreement.
function pause() public onlyOwners() {
_pause();
}
/// @dev Create a resolution to unpause the contract. Performs update if threshold is 1 or zero.
function createResolutionUnpause() public onlyOwners() {
createResolution(resTypeUnpause, address(1), address(1), new bytes32[](0));
}
// ////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
// ////////////////////////////////////////////////////
/// @dev Create a resolution and check if we can call perofrm the resolution with 1 vote.
function createResolution(
uint256 resType,
address oldAddress,
address newAddress,
bytes32[] memory extra
) internal {
uint256 resNum = nextResolution;
nextResolution++;
resolutionAlreadyUsed(resNum);
resolutions[resNum].resType = resType;
resolutions[resNum].oldAddress = oldAddress;
resolutions[resNum].newAddress = newAddress;
resolutions[resNum].extra = extra;
ownerVotes[msg.sender][resNum] = true;
lastOwnerResolutionNumber[msg.sender] = resNum;
// Check if agreement is already reached
if (ownerAgreementThreshold <= 1) {
_performResolution(resNum);
}
}
/// @dev Performs the resolution and then marks it as passed. No checks prevent it from performing the resolutions.
function _performResolution(uint256 resNum) internal {
if (resolutions[resNum].resType == resTypeAddOwner) {
_addOwner(resolutions[resNum].newAddress);
} else if (resolutions[resNum].resType == resTypeRemoveOwner) {
_removeOwner(resolutions[resNum].oldAddress);
} else if (resolutions[resNum].resType == resTypeReplaceOwner) {
_replaceOwner(
resolutions[resNum].oldAddress,
resolutions[resNum].newAddress
);
} else if (resolutions[resNum].resType == resTypeAddOperator) {
_addOperator(resolutions[resNum].newAddress);
} else if (resolutions[resNum].resType == resTypeRemoveOperator) {
_removeOperator(resolutions[resNum].oldAddress);
} else if (resolutions[resNum].resType == resTypeReplaceOperator) {
_replaceOperator(
resolutions[resNum].oldAddress,
resolutions[resNum].newAddress
);
} else if (
resolutions[resNum].resType == resTypeUpdateTransactionLimit
) {
_updateTransactionLimit(uint160(resolutions[resNum].newAddress));
} else if (resolutions[resNum].resType == resTypeUpdateThreshold) {
_updateThreshold(uint160(resolutions[resNum].newAddress));
} else if (resolutions[resNum].resType == resTypePause) {
_pause();
} else if (resolutions[resNum].resType == resTypeUnpause) {
_unpause();
} else {
_customResolutions(resNum);
return;
}
resolutions[resNum].passed = true;
}
/**
* @dev Able to handle Custom Resolutions.
*
* Requirements:
*
* - Must set the resolution passed: resolutions[resNum].passed = true;
* - You should check the resolutions[resNum].resType to know what to perform
*/
function _customResolutions(uint256 resNum) internal virtual {}
/// @dev
function _addOwner(address newOwner) internal {
EnumerableSet.add(_owners, newOwner);
emit OwnerAddition(newOwner);
}
/// @dev
function _removeOwner(address newOwner) internal {
EnumerableSet.remove(_owners, newOwner);
emit OwnerRemoval(newOwner);
uint numOwners = getNumberOfOwners();
if (ownerAgreementThreshold > numOwners) {
_updateThreshold(numOwners);
}
}
/// @dev
function _replaceOwner(address oldOwner, address newOwner) internal {
EnumerableSet.remove(_owners, oldOwner);
EnumerableSet.add(_owners, newOwner);
emit OwnerReplacement(oldOwner, newOwner);
}
/// @dev
function _addOperator(address operator) internal {
EnumerableSet.add(_operators, operator);
emit OperatorAddition(operator);
}
/// @dev
function _removeOperator(address operator) internal {
EnumerableSet.remove(_operators, operator);
emit OperatorRemoval(operator);
}
/// @dev
function _replaceOperator(address oldOperator, address newOperator)
internal
{
emit OperatorReplacement(oldOperator, newOperator);
EnumerableSet.remove(_operators, oldOperator);
EnumerableSet.add(_operators, newOperator);
}
/// @dev Internal function to update and emit the new transaction limit
function _updateTransactionLimit(uint256 newLimit) internal {
emit UpdateTransactionLimit(newLimit);
transactionLimit = newLimit;
}
/// @dev Internal function to update and emit the new voting threshold
function _updateThreshold(uint threshold) internal {
require(
threshold <= getNumberOfOwners(),
"Unable to set threshold above the number of owners"
);
emit UpdateThreshold(threshold);
ownerAgreementThreshold = threshold;
}
/// @dev Internal function to update and emit the new voting threshold
function _updateNumberOfOperators(uint160 numOperators) internal {
require(
numOperators >= getNumberOfOperators(),
"Unable to set number of Operators below the number of operators"
);
emit UpdateNumberOfOperators(numOperators);
operatorLimit = numOperators;
}
/**
* @dev Triggers stopped state.
*
* Requirements: The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Returns to normal state.
*
* Requirements: The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: contracts/UreeqaRandomNumberv1.sol
pragma solidity >=0.7.0 <0.9.0;
/// @title Random Numbers by UREEQA.
/// @author Dr. Jonathan Shahen at UREEQA
/// @notice Random number generatation for UREEQA that utilizes ChainLink
/// @dev Utilize the block number if you require to check state of other smart contracts
contract UreeqaRandomNumberv1 is OwnershipAgreementv3, VRFConsumerBase {
// ////////////////////////////////////////////////////
// STORAGE
// ////////////////////////////////////////////////////
struct RandomNumber {
uint256 id;
bytes32 fileHash;
bytes32 requestId;
uint256 blockTime;
uint256 blockNumber;
uint256 randomNumber;
}
// ChainLink settings
bytes32 keyHash;
// How much LINK it costs for a random number
uint256 fee;
// Store all the staked content. ID => RandomNumber
mapping(uint256 => RandomNumber) randomNumbers;
// Store all the staked content. ID => RandomNumber
mapping(bytes32 => uint256) requestIdToId;
// Last ID Used
uint256 lastId;
// Number of Random Numbers
uint256 numberOfRandomNumbers;
// Reference filehash to id
mapping(bytes32 => uint256) hashToId;
// ////////////////////////////////////////////////////
// CONSTRUCTOR
// ////////////////////////////////////////////////////
constructor(
address vrfCoordinator,
address linkToken,
bytes32 _keyHash,
uint256 _fee,
address operator
) VRFConsumerBase(vrfCoordinator, linkToken) {
keyHash = _keyHash;
fee = _fee;
if (operator != address(0)) {
createResolutionAddOperator(operator);
}
}
// ////////////////////////////////////////////////////
// EVENTS
// ////////////////////////////////////////////////////
event NewRandomNumber(uint256 id, bytes32 fileHash);
event RandomNumberGenerated(
uint256 id,
bytes32 fileHash,
uint256 blockNumber,
uint256 randomNumber
);
event FileHashChanged(
uint256 id,
bytes32 old_fileHash,
bytes32 new_fileHash
);
// ////////////////////////////////////////////////////
// MODIFIERS
// ////////////////////////////////////////////////////
modifier nonZeroId(uint256 id) {
require(id != 0, "Content Staking ID cannot be 0.");
_;
}
modifier nonZeroFileHash(bytes32 fileHash) {
require(fileHash != 0, "File hash cannot be 0.");
_;
}
modifier idMustExists(uint256 id) {
require(randomNumbers[id].id != 0, "ID does not exists");
_;
}
modifier idMustBeUnique(uint256 id) {
require(randomNumbers[id].id == 0, "ID must be unique");
_;
}
modifier hashMustBeUnique(bytes32 fileHash) {
require(hashToId[fileHash] == 0, "File Hash must be unique");
_;
}
// ////////////////////////////////////////////////////
// VIEW FUNCTIONS
// ////////////////////////////////////////////////////
/// @dev Returns the last id that was created
function getLastId() public view returns (uint256) {
return lastId;
}
/// @dev Get the ID from a filehash
function getId(bytes32 fileHash)
public
view
nonZeroFileHash(fileHash)
returns (uint256)
{
return hashToId[fileHash];
}
/// @dev Get the ID from a filehash
function getFileHash(uint256 id)
public
view
nonZeroId(id)
idMustExists(id)
returns (bytes32)
{
return randomNumbers[id].fileHash;
}
/// @dev Get the Block Time when the random number was generated
function getBlockTime(uint256 id)
public
view
nonZeroId(id)
idMustExists(id)
returns (uint256)
{
return randomNumbers[id].blockTime;
}
/// @dev Get the Block Number when the random number was generated
function getBlockNumber(uint256 id)
public
view
nonZeroId(id)
idMustExists(id)
returns (uint256)
{
return randomNumbers[id].blockNumber;
}
/// @dev Return the generated random number. Zero represents a non-generated number.
function getRandomNumber(uint256 id)
public
view
nonZeroId(id)
idMustExists(id)
returns (uint256)
{
return randomNumbers[id].randomNumber;
}
// ////////////////////////////////////////////////////
// PUBLIC/OPERATOR FUNCTIONS
// ////////////////////////////////////////////////////
/// @dev Creates a new random number
function newRandomNumber(uint256 id, bytes32 fileHash)
public
onlyOperators()
nonZeroId(id)
idMustBeUnique(id)
nonZeroFileHash(fileHash)
hashMustBeUnique(fileHash)
{
randomNumbers[id].id = id;
randomNumbers[id].fileHash = fileHash;
emit NewRandomNumber(id, fileHash);
hashToId[fileHash] = id;
lastId = id;
numberOfRandomNumbers += 1;
}
/// @dev Bulk creation to reduce gas fees.
function bulkRandomNumbers(
uint256[] memory ids,
bytes32[] memory fileHashes
) public onlyOperators() {
require(
ids.length == fileHashes.length,
"Arrays must be the same length"
);
for (uint256 i = 0; i < ids.length; i++) {
newRandomNumber(ids[i], fileHashes[i]);
}
}
/// @dev Generate the random number
function generateRandomNumber(uint256 id)
public
onlyOperators()
nonZeroId(id)
idMustExists(id)
{
require(
randomNumbers[id].requestId == 0,
"Request already exists for this ID."
);
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK");
bytes32 requestId = requestRandomness(keyHash, fee);
randomNumbers[id].requestId = requestId;
requestIdToId[requestId] = id;
}
/// @dev Generate the random numbers
function bulkGenerateRandomNumbers(uint256[] memory ids)
public
onlyOperators()
{
require(
LINK.balanceOf(address(this)) >= fee * ids.length,
"Not enough LINK"
);
for (uint256 i = 0; i < ids.length; i++) {
require(ids[i] != 0, "ID cannot be 0");
require(randomNumbers[ids[i]].fileHash != 0, "ID does not exists");
require(
randomNumbers[ids[i]].requestId == 0,
"Request already exists for this ID."
);
bytes32 requestId = requestRandomness(keyHash, fee);
randomNumbers[ids[i]].requestId = requestId;
requestIdToId[requestId] = ids[i];
}
}
// ////////////////////////////////////////////////////
// OWNER FUNCTIONS
// ////////////////////////////////////////////////////
/// @dev Update a file hash, resets the old file hash.
function updateFileHash(uint256 id, bytes32 newFileHash)
public
onlyOwners()
nonZeroId(id)
idMustExists(id)
{
bytes32 oldFileHash = randomNumbers[id].fileHash;
emit FileHashChanged(id, oldFileHash, newFileHash);
randomNumbers[id].fileHash = newFileHash;
hashToId[oldFileHash] = 0;
hashToId[newFileHash] = id;
}
/// @dev transfer LINK tokens from this contract to another address
function transferLINK(address sendTo, uint256 amount) public onlyOwners() {
LINK.transfer(sendTo, amount);
}
/// @dev updates the CHAINLINK fee
function updateLINKFee(uint256 new_fee) public onlyOwners() {
fee = new_fee;
}
// ////////////////////////////////////////////////////
// CHAINLINK FUNCTIONS
// ////////////////////////////////////////////////////
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
randomNumbers[requestIdToId[requestId]].randomNumber = randomness;
randomNumbers[requestIdToId[requestId]].blockTime = block.timestamp;
randomNumbers[requestIdToId[requestId]].blockNumber = block.number;
emit RandomNumberGenerated(
requestIdToId[requestId],
randomNumbers[requestIdToId[requestId]].fileHash,
randomNumbers[requestIdToId[requestId]].blockNumber,
randomNumbers[requestIdToId[requestId]].randomNumber
);
}
// ////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
// ////////////////////////////////////////////////////
}
|
Generate the random numbers
|
function bulkGenerateRandomNumbers(uint256[] memory ids)
public
onlyOperators()
{
require(
LINK.balanceOf(address(this)) >= fee * ids.length,
"Not enough LINK"
);
for (uint256 i = 0; i < ids.length; i++) {
require(ids[i] != 0, "ID cannot be 0");
require(randomNumbers[ids[i]].fileHash != 0, "ID does not exists");
require(
randomNumbers[ids[i]].requestId == 0,
"Request already exists for this ID."
);
bytes32 requestId = requestRandomness(keyHash, fee);
randomNumbers[ids[i]].requestId = requestId;
requestIdToId[requestId] = ids[i];
}
}
| 6,338,763 |
/*
Copyright (c) 2018, ZSC Dev Team
*/
pragma solidity ^0.4.21;
import "./sys_gm_base.sol";
/** @title String manager. */
contract SysGmString is SysGmBase {
// parameter mapping string
struct ParameterValues {
uint count_;
// index => parameter
mapping(uint => bytes32) parameters_;
// parameter => index
mapping(bytes32 => uint) indexs_;
// parameter => register
mapping(bytes32 => bool) registers_;
// parameter => string
mapping(bytes32 => string) strings_;
}
// user holder info
struct UserHolderInfo {
address holder_;
mapping(address => bool) multisig_;
}
// database name => user name => entity name => parameter value
mapping(bytes32 => mapping(bytes32 => mapping(bytes32 => ParameterValues))) private entitys_;
// database name => user name => holder
mapping(bytes32 => mapping(bytes32 => UserHolderInfo)) private userHolders_;
// constructor
function SysGmString(bytes32 _name) public SysGmBase(_name) {}
// check holder.
function _checkHolder(bytes32 _dbName, bytes32 _userName, address _holder) private view {
require(_holder == userHolders_[_dbName][_userName].holder_);
}
/** @dev Register holder.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _holder(address): Address of the holder.
* @return none.
*/
function registerHolder(bytes32 _dbName, bytes32 _userName, address _holder) external {
checkDelegate(msg.sender, 1);
userHolders_[_dbName][_userName].holder_ = _holder;
}
/** @dev Add parameter.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _enName(bytes32): Name of the entity.
* @param _parameter(bytes32): Name of parameter.
* @return (bool): The result(true/false).
*/
function addEntityParameter(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName, bytes32 _parameter) external returns (bool) {
// check holder
_checkHolder(_dbName, _userName, msg.sender);
// check register
if(true == entitys_[_dbName][_userName][_enName].registers_[_parameter]) {
return true;
}
uint count = entitys_[_dbName][_userName][_enName].count_;
entitys_[_dbName][_userName][_enName].parameters_[count] = _parameter;
entitys_[_dbName][_userName][_enName].indexs_[_parameter] = count;
entitys_[_dbName][_userName][_enName].registers_[_parameter] = true;
entitys_[_dbName][_userName][_enName].count_ ++;
return true;
}
/** @dev Set string.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _enName(bytes32): Name of the entity.
* @param _parameter(bytes32): Name of parameter.
* @param _value(string): Value of string.
* @return (bool): The result(true/false).
*/
function setEntityParameterValue(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName, bytes32 _parameter, string _value) external returns (bool) {
// check holder
_checkHolder(_dbName, _userName, msg.sender);
// check register
if(false == entitys_[_dbName][_userName][_enName].registers_[_parameter]) {
require(addEntityParameter(_dbName, _userName, _enName, _parameter));
}
entitys_[_dbName][_userName][_enName].strings_[_parameter] = _value;
return true;
}
/** @dev Get number of string.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _enName(bytes32): Name of the entity.
* @return (uint): Number of string.
*/
function numEntityParameters(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName) external view returns (uint) {
// check holder
_checkHolder(_dbName, _userName, msg.sender);
return entitys_[_dbName][_userName][_enName].count_;
}
/** @dev Get string.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _enName(bytes32): Name of the entity.
* @param _parameter(bytes32): Name of parameter.
* @return (string): Value of string.
*/
function getEntityParameterValue(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName, bytes32 _parameter) external view returns (string) {
// check holder
_checkHolder(_dbName, _userName, msg.sender);
// check register
require(entitys_[_dbName][_userName][_enName].registers_[_parameter]);
string memory str = entitys_[_dbName][_userName][_enName].strings_[_parameter];
return str;
}
/** @dev Get parameter by index.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _enName(bytes32): Name of the entity.
* @param _index(uint): index of parameter.
* @return (bytes32): Name of parameter.
*/
function getEntityParameterByIndex(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName, uint _index) external view returns (bytes32) {
// check holder
_checkHolder(_dbName, _userName, msg.sender);
// check param
require(entitys_[_dbName][_userName][_enName].count_ >= (_index + 1));
bytes32 parameter = entitys_[_dbName][_userName][_enName].parameters_[_index];
// check register
require(entitys_[_dbName][_userName][_enName].registers_[parameter]);
return parameter;
}
/** @dev Remove string.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _enName(bytes32): Name of the entity.
* @param _parameter(bytes32): Name of parameter.
* @return (bool): The result(true/false).
*/
function removeEntityParameterValue(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName, bytes32 _parameter) external returns (bool) {
// check holder
_checkHolder(_dbName, _userName, msg.sender);
// check register
require(entitys_[_dbName][_userName][_enName].registers_[_parameter]);
uint index = entitys_[_dbName][_userName][_enName].indexs_[_parameter];
delete entitys_[_dbName][_userName][_enName].parameters_[index];
delete entitys_[_dbName][_userName][_enName].indexs_[_parameter];
delete entitys_[_dbName][_userName][_enName].registers_[_parameter];
delete entitys_[_dbName][_userName][_enName].strings_[_parameter];
return true;
}
/** @dev Remove string by index.
* @param _dbName(bytes32): Name of the database.
* @param _userName(bytes32): Name of the user.
* @param _enName(bytes32): Name of the entity.
* @param _index(uint): Index of parameter.
* @return (bool): The result(true/false).
*/
function removeEntityParameterValueByIndex(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName, uint _index) external returns (bool) {
// check holder
_checkHolder(_dbName, _userName, msg.sender);
// check param
require(entitys_[_dbName][_userName][_enName].count_ >= (_index + 1));
bytes32 parameter = entitys_[_dbName][_userName][_enName].parameters_[_index];
// check register
require(entitys_[_dbName][_userName][_enName].registers_[parameter]);
return removeEntityParameterValue(_dbName, _userName, _enName, parameter);
}
}
|
Set string. _dbName(bytes32): Name of the database. _userName(bytes32): Name of the user. _enName(bytes32): Name of the entity. _parameter(bytes32): Name of parameter. _value(string): Value of string. return (bool): The result(true/false)./ check holder check register
|
function setEntityParameterValue(
bytes32 _dbName, bytes32 _userName,
bytes32 _enName, bytes32 _parameter, string _value) external returns (bool) {
_checkHolder(_dbName, _userName, msg.sender);
if(false == entitys_[_dbName][_userName][_enName].registers_[_parameter]) {
require(addEntityParameter(_dbName, _userName, _enName, _parameter));
}
entitys_[_dbName][_userName][_enName].strings_[_parameter] = _value;
return true;
}
| 2,486,669 |
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: RewardEscrowV2.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/RewardEscrowV2.sol
* Docs: https://docs.synthetix.io/contracts/RewardEscrowV2
*
* Contract Dependencies:
* - BaseRewardEscrowV2
* - IAddressResolver
* - Owned
* Libraries:
* - SafeDecimalMath
* - SafeMath
* - VestingEntries
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.synthetix.io/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination = resolver.requireAndGetAddress(
name,
string(abi.encodePacked("Resolver missing target: ", name))
);
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/contracts/limitedsetup
contract LimitedSetup {
uint public setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration) internal {
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup {
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
pragma experimental ABIEncoderV2;
library VestingEntries {
struct VestingEntry {
uint64 endTime;
uint256 escrowAmount;
}
struct VestingEntryWithID {
uint64 endTime;
uint256 escrowAmount;
uint256 entryID;
}
}
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint);
function getVestingSchedules(
address account,
uint256 index,
uint256 pageSize
) external view returns (VestingEntries.VestingEntryWithID[] memory);
function getAccountVestingEntryIDs(
address account,
uint256 index,
uint256 pageSize
) external view returns (uint256[] memory);
function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint);
function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256);
// Mutative functions
function vest(uint256[] calldata entryIDs) external;
function createEscrowEntry(
address beneficiary,
uint256 deposit,
uint256 duration
) external;
function appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) external;
function migrateVestingSchedule(address _addressToMigrate) external;
function migrateAccountEscrowBalances(
address[] calldata accounts,
uint256[] calldata escrowBalances,
uint256[] calldata vestedBalances
) external;
// Account Merging
function startMergingWindow() external;
function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external;
function nominateAccountToMerge(address account) external;
function accountMergingIsOpen() external view returns (bool);
// L2 Migration
function importVestingEntries(
address account,
uint256 escrowedAmount,
VestingEntries.VestingEntry[] calldata vestingEntries
) external;
// Return amount of SNX transfered to SynthetixBridgeToOptimism deposit contract
function burnForMigration(address account, uint256[] calldata entryIDs)
external
returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
interface IVirtualSynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function synth() external view returns (ISynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isynthetix
interface ISynthetix {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint);
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey) external view returns (uint);
function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint);
function transferableSynthetix(address account) external view returns (uint transferable);
// Mutative Functions
function burnSynths(uint amount) external;
function burnSynthsOnBehalf(address burnForAddress, uint amount) external;
function burnSynthsToTarget() external;
function burnSynthsToTargetOnBehalf(address burnForAddress) external;
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function issueMaxSynths() external;
function issueMaxSynthsOnBehalf(address issueForAddress) external;
function issueSynths(uint amount) external;
function issueSynthsOnBehalf(address issueForAddress, uint amount) external;
function mint() external returns (bool);
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
// Liquidations
function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool);
// Restricted Functions
function mintSecondary(address account, uint amount) external;
function mintSecondaryRewards(uint amount) external;
function burnSecondary(address account, uint amount) external;
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/RewardEscrow
contract BaseRewardEscrowV2 is Owned, IRewardEscrowV2, LimitedSetup(8 weeks), MixinResolver {
using SafeMath for uint;
using SafeDecimalMath for uint;
mapping(address => mapping(uint256 => VestingEntries.VestingEntry)) public vestingSchedules;
mapping(address => uint256[]) public accountVestingEntryIDs;
/*Counter for new vesting entry ids. */
uint256 public nextEntryId;
/* An account's total escrowed synthetix balance to save recomputing this for fee extraction purposes. */
mapping(address => uint256) public totalEscrowedAccountBalance;
/* An account's total vested reward synthetix. */
mapping(address => uint256) public totalVestedAccountBalance;
/* Mapping of nominated address to recieve account merging */
mapping(address => address) public nominatedReceiver;
/* The total remaining escrowed balance, for verifying the actual synthetix balance of this contract against. */
uint256 public totalEscrowedBalance;
/* Max escrow duration */
uint public max_duration = 2 * 52 weeks; // Default max 2 years duration
/* Max account merging duration */
uint public maxAccountMergingDuration = 4 weeks; // Default 4 weeks is max
/* ========== ACCOUNT MERGING CONFIGURATION ========== */
uint public accountMergingDuration = 1 weeks;
uint public accountMergingStartTime;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver) {
nextEntryId = 1;
}
/* ========== VIEWS ======================= */
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function synthetix() internal view returns (ISynthetix) {
return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function _notImplemented() internal pure {
revert("Cannot be run on this layer");
}
/* ========== VIEW FUNCTIONS ========== */
// Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](3);
addresses[0] = CONTRACT_SYNTHETIX;
addresses[1] = CONTRACT_FEEPOOL;
addresses[2] = CONTRACT_ISSUER;
}
/**
* @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account) public view returns (uint) {
return totalEscrowedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account) external view returns (uint) {
return accountVestingEntryIDs[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return The vesting entry object and rate per second emission.
*/
function getVestingEntry(address account, uint256 entryID) external view returns (uint64 endTime, uint256 escrowAmount) {
endTime = vestingSchedules[account][entryID].endTime;
escrowAmount = vestingSchedules[account][entryID].escrowAmount;
}
function getVestingSchedules(
address account,
uint256 index,
uint256 pageSize
) external view returns (VestingEntries.VestingEntryWithID[] memory) {
uint256 endIndex = index + pageSize;
// If index starts after the endIndex return no results
if (endIndex <= index) {
return new VestingEntries.VestingEntryWithID[](0);
}
// If the page extends past the end of the accountVestingEntryIDs, truncate it.
if (endIndex > accountVestingEntryIDs[account].length) {
endIndex = accountVestingEntryIDs[account].length;
}
uint256 n = endIndex - index;
VestingEntries.VestingEntryWithID[] memory vestingEntries = new VestingEntries.VestingEntryWithID[](n);
for (uint256 i; i < n; i++) {
uint256 entryID = accountVestingEntryIDs[account][i + index];
VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID];
vestingEntries[i] = VestingEntries.VestingEntryWithID({
endTime: uint64(entry.endTime),
escrowAmount: entry.escrowAmount,
entryID: entryID
});
}
return vestingEntries;
}
function getAccountVestingEntryIDs(
address account,
uint256 index,
uint256 pageSize
) external view returns (uint256[] memory) {
uint256 endIndex = index + pageSize;
// If the page extends past the end of the accountVestingEntryIDs, truncate it.
if (endIndex > accountVestingEntryIDs[account].length) {
endIndex = accountVestingEntryIDs[account].length;
}
if (endIndex <= index) {
return new uint256[](0);
}
uint256 n = endIndex - index;
uint256[] memory page = new uint256[](n);
for (uint256 i; i < n; i++) {
page[i] = accountVestingEntryIDs[account][i + index];
}
return page;
}
function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint total) {
for (uint i = 0; i < entryIDs.length; i++) {
VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryIDs[i]];
/* Skip entry if escrowAmount == 0 */
if (entry.escrowAmount != 0) {
uint256 quantity = _claimableAmount(entry);
/* add quantity to total */
total = total.add(quantity);
}
}
}
function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint) {
VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID];
return _claimableAmount(entry);
}
function _claimableAmount(VestingEntries.VestingEntry memory _entry) internal view returns (uint256) {
uint256 quantity;
if (_entry.escrowAmount != 0) {
/* Escrow amounts claimable if block.timestamp equal to or after entry endTime */
quantity = block.timestamp >= _entry.endTime ? _entry.escrowAmount : 0;
}
return quantity;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* Vest escrowed amounts that are claimable
* Allows users to vest their vesting entries based on msg.sender
*/
function vest(uint256[] calldata entryIDs) external {
uint256 total;
for (uint i = 0; i < entryIDs.length; i++) {
VestingEntries.VestingEntry storage entry = vestingSchedules[msg.sender][entryIDs[i]];
/* Skip entry if escrowAmount == 0 already vested */
if (entry.escrowAmount != 0) {
uint256 quantity = _claimableAmount(entry);
/* update entry to remove escrowAmount */
if (quantity > 0) {
entry.escrowAmount = 0;
}
/* add quantity to total */
total = total.add(quantity);
}
}
/* Transfer vested tokens. Will revert if total > totalEscrowedAccountBalance */
if (total != 0) {
_transferVestedTokens(msg.sender, total);
}
}
/**
* @notice Create an escrow entry to lock SNX for a given duration in seconds
* @dev This call expects that the depositor (msg.sender) has already approved the Reward escrow contract
to spend the the amount being escrowed.
*/
function createEscrowEntry(
address beneficiary,
uint256 deposit,
uint256 duration
) external {
require(beneficiary != address(0), "Cannot create escrow with address(0)");
/* Transfer SNX from msg.sender */
require(IERC20(address(synthetix())).transferFrom(msg.sender, address(this), deposit), "token transfer failed");
/* Append vesting entry for the beneficiary address */
_appendVestingEntry(beneficiary, deposit, duration);
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should accompany a previous successful call to synthetix.transfer(rewardEscrow, amount),
* to ensure that when the funds are withdrawn, there is enough balance.
* @param account The account to append a new vesting entry to.
* @param quantity The quantity of SNX that will be escrowed.
* @param duration The duration that SNX will be emitted.
*/
function appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) external onlyFeePool {
_appendVestingEntry(account, quantity, duration);
}
/* Transfer vested tokens and update totalEscrowedAccountBalance, totalVestedAccountBalance */
function _transferVestedTokens(address _account, uint256 _amount) internal {
_reduceAccountEscrowBalances(_account, _amount);
totalVestedAccountBalance[_account] = totalVestedAccountBalance[_account].add(_amount);
IERC20(address(synthetix())).transfer(_account, _amount);
emit Vested(_account, block.timestamp, _amount);
}
function _reduceAccountEscrowBalances(address _account, uint256 _amount) internal {
// Reverts if amount being vested is greater than the account's existing totalEscrowedAccountBalance
totalEscrowedBalance = totalEscrowedBalance.sub(_amount);
totalEscrowedAccountBalance[_account] = totalEscrowedAccountBalance[_account].sub(_amount);
}
/* ========== ACCOUNT MERGING ========== */
function accountMergingIsOpen() public view returns (bool) {
return accountMergingStartTime.add(accountMergingDuration) > block.timestamp;
}
function startMergingWindow() external onlyOwner {
accountMergingStartTime = block.timestamp;
emit AccountMergingStarted(accountMergingStartTime, accountMergingStartTime.add(accountMergingDuration));
}
function setAccountMergingDuration(uint256 duration) external onlyOwner {
require(duration <= maxAccountMergingDuration, "exceeds max merging duration");
accountMergingDuration = duration;
emit AccountMergingDurationUpdated(duration);
}
function setMaxAccountMergingWindow(uint256 duration) external onlyOwner {
maxAccountMergingDuration = duration;
emit MaxAccountMergingDurationUpdated(duration);
}
function setMaxEscrowDuration(uint256 duration) external onlyOwner {
max_duration = duration;
emit MaxEscrowDurationUpdated(duration);
}
/* Nominate an account to merge escrow and vesting schedule */
function nominateAccountToMerge(address account) external {
require(account != msg.sender, "Cannot nominate own account to merge");
require(accountMergingIsOpen(), "Account merging has ended");
require(issuer().debtBalanceOf(msg.sender, "sUSD") == 0, "Cannot merge accounts with debt");
nominatedReceiver[msg.sender] = account;
emit NominateAccountToMerge(msg.sender, account);
}
function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external {
require(accountMergingIsOpen(), "Account merging has ended");
require(issuer().debtBalanceOf(accountToMerge, "sUSD") == 0, "Cannot merge accounts with debt");
require(nominatedReceiver[accountToMerge] == msg.sender, "Address is not nominated to merge");
uint256 totalEscrowAmountMerged;
for (uint i = 0; i < entryIDs.length; i++) {
// retrieve entry
VestingEntries.VestingEntry memory entry = vestingSchedules[accountToMerge][entryIDs[i]];
/* ignore vesting entries with zero escrowAmount */
if (entry.escrowAmount != 0) {
/* copy entry to msg.sender (destination address) */
vestingSchedules[msg.sender][entryIDs[i]] = entry;
/* Add the escrowAmount of entry to the totalEscrowAmountMerged */
totalEscrowAmountMerged = totalEscrowAmountMerged.add(entry.escrowAmount);
/* append entryID to list of entries for account */
accountVestingEntryIDs[msg.sender].push(entryIDs[i]);
/* Delete entry from accountToMerge */
delete vestingSchedules[accountToMerge][entryIDs[i]];
}
}
/* update totalEscrowedAccountBalance for merged account and accountToMerge */
totalEscrowedAccountBalance[accountToMerge] = totalEscrowedAccountBalance[accountToMerge].sub(
totalEscrowAmountMerged
);
totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].add(totalEscrowAmountMerged);
emit AccountMerged(accountToMerge, msg.sender, totalEscrowAmountMerged, entryIDs, block.timestamp);
}
/* Internal function for importing vesting entry and creating new entry for escrow liquidations */
function _addVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal returns (uint) {
uint entryID = nextEntryId;
vestingSchedules[account][entryID] = entry;
/* append entryID to list of entries for account */
accountVestingEntryIDs[account].push(entryID);
/* Increment the next entry id. */
nextEntryId = nextEntryId.add(1);
return entryID;
}
/* ========== MIGRATION OLD ESCROW ========== */
function migrateVestingSchedule(address) external {
_notImplemented();
}
function migrateAccountEscrowBalances(
address[] calldata,
uint256[] calldata,
uint256[] calldata
) external {
_notImplemented();
}
/* ========== L2 MIGRATION ========== */
function burnForMigration(address, uint[] calldata) external returns (uint256, VestingEntries.VestingEntry[] memory) {
_notImplemented();
}
function importVestingEntries(
address,
uint256,
VestingEntries.VestingEntry[] calldata
) external {
_notImplemented();
}
/* ========== INTERNALS ========== */
function _appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) internal {
/* No empty or already-passed vesting entries allowed. */
require(quantity != 0, "Quantity cannot be zero");
require(duration > 0 && duration <= max_duration, "Cannot escrow with 0 duration OR above max_duration");
/* There must be enough balance in the contract to provide for the vesting entry. */
totalEscrowedBalance = totalEscrowedBalance.add(quantity);
require(
totalEscrowedBalance <= IERC20(address(synthetix())).balanceOf(address(this)),
"Must be enough balance in the contract to provide for the vesting entry"
);
/* Escrow the tokens for duration. */
uint endTime = block.timestamp + duration;
/* Add quantity to account's escrowed balance */
totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity);
uint entryID = nextEntryId;
vestingSchedules[account][entryID] = VestingEntries.VestingEntry({endTime: uint64(endTime), escrowAmount: quantity});
accountVestingEntryIDs[account].push(entryID);
/* Increment the next entry id. */
nextEntryId = nextEntryId.add(1);
emit VestingEntryCreated(account, block.timestamp, quantity, duration, entryID);
}
/* ========== MODIFIERS ========== */
modifier onlyFeePool() {
require(msg.sender == address(feePool()), "Only the FeePool can perform this action");
_;
}
/* ========== EVENTS ========== */
event Vested(address indexed beneficiary, uint time, uint value);
event VestingEntryCreated(address indexed beneficiary, uint time, uint value, uint duration, uint entryID);
event MaxEscrowDurationUpdated(uint newDuration);
event MaxAccountMergingDurationUpdated(uint newDuration);
event AccountMergingDurationUpdated(uint newDuration);
event AccountMergingStarted(uint time, uint endTime);
event AccountMerged(
address indexed accountToMerge,
address destinationAddress,
uint escrowAmountMerged,
uint[] entryIDs,
uint time
);
event NominateAccountToMerge(address indexed account, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/irewardescrow
interface IRewardEscrow {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory);
function getNextVestingIndex(address account) external view returns (uint);
// Mutative functions
function appendVestingEntry(address account, uint quantity) external;
function vest() external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/RewardEscrow
contract RewardEscrowV2 is BaseRewardEscrowV2 {
mapping(address => uint256) public totalBalancePendingMigration;
uint public migrateEntriesThresholdAmount = SafeDecimalMath.unit() * 1000; // Default 1000 SNX
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYNTHETIX_BRIDGE_OPTIMISM = "SynthetixBridgeToOptimism";
bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, address _resolver) public BaseRewardEscrowV2(_owner, _resolver) {}
/* ========== VIEWS ======================= */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = BaseRewardEscrowV2.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](3);
newAddresses[0] = CONTRACT_SYNTHETIX_BRIDGE_OPTIMISM;
newAddresses[1] = CONTRACT_REWARD_ESCROW;
newAddresses[2] = CONTRACT_SYSTEMSTATUS;
return combineArrays(existingAddresses, newAddresses);
}
function synthetixBridgeToOptimism() internal view returns (address) {
return requireAndGetAddress(CONTRACT_SYNTHETIX_BRIDGE_OPTIMISM);
}
function oldRewardEscrow() internal view returns (IRewardEscrow) {
return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
/* ========== OLD ESCROW LOOKUP ========== */
uint internal constant TIME_INDEX = 0;
uint internal constant QUANTITY_INDEX = 1;
/* ========== MIGRATION OLD ESCROW ========== */
/* Threshold amount for migrating escrow entries from old RewardEscrow */
function setMigrateEntriesThresholdAmount(uint amount) external onlyOwner {
migrateEntriesThresholdAmount = amount;
emit MigrateEntriesThresholdAmountUpdated(amount);
}
/* Function to allow any address to migrate vesting entries from previous reward escrow */
function migrateVestingSchedule(address addressToMigrate) external systemActive {
/* Ensure account escrow balance pending migration is not zero */
/* Ensure account escrowed balance is not zero - should have been migrated */
require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending");
require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0");
/* Add a vestable entry for addresses with totalBalancePendingMigration <= migrateEntriesThreshold amount of SNX */
if (totalBalancePendingMigration[addressToMigrate] <= migrateEntriesThresholdAmount) {
_importVestingEntry(
addressToMigrate,
VestingEntries.VestingEntry({
endTime: uint64(block.timestamp),
escrowAmount: totalBalancePendingMigration[addressToMigrate]
})
);
/* Remove totalBalancePendingMigration[addressToMigrate] */
delete totalBalancePendingMigration[addressToMigrate];
} else {
uint numEntries = oldRewardEscrow().numVestingEntries(addressToMigrate);
/* iterate and migrate old escrow schedules from rewardEscrow.vestingSchedules
* starting from the last entry in each staker's vestingSchedules
*/
for (uint i = 1; i <= numEntries; i++) {
uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i);
uint time = vestingSchedule[TIME_INDEX];
uint amount = vestingSchedule[QUANTITY_INDEX];
/* The list is sorted, when we reach the first entry that can be vested stop */
if (time < block.timestamp) {
break;
}
/* import vesting entry */
_importVestingEntry(
addressToMigrate,
VestingEntries.VestingEntry({endTime: uint64(time), escrowAmount: amount})
);
/* subtract amount from totalBalancePendingMigration - reverts if insufficient */
totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub(amount);
}
}
}
/**
* Import function for owner to import vesting schedule
* All entries imported should have past their vesting timestamp and will be ready to be vested
* Addresses with totalEscrowedAccountBalance == 0 will not be migrated as they have all vested
*/
function importVestingSchedule(address[] calldata accounts, uint256[] calldata escrowAmounts)
external
onlyDuringSetup
onlyOwner
{
require(accounts.length == escrowAmounts.length, "Account and escrowAmounts Length mismatch");
for (uint i = 0; i < accounts.length; i++) {
address addressToMigrate = accounts[i];
uint256 escrowAmount = escrowAmounts[i];
// ensure account have escrow migration pending
require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0");
require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending");
/* Import vesting entry with endTime as block.timestamp and escrowAmount */
_importVestingEntry(
addressToMigrate,
VestingEntries.VestingEntry({endTime: uint64(block.timestamp), escrowAmount: escrowAmount})
);
/* update totalBalancePendingMigration - reverts if escrowAmount > remaining balance to migrate */
totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub(
escrowAmount
);
emit ImportedVestingSchedule(addressToMigrate, block.timestamp, escrowAmount);
}
}
/**
* Migration for owner to migrate escrowed and vested account balances
* Addresses with totalEscrowedAccountBalance == 0 will not be migrated as they have all vested
*/
function migrateAccountEscrowBalances(
address[] calldata accounts,
uint256[] calldata escrowBalances,
uint256[] calldata vestedBalances
) external onlyDuringSetup onlyOwner {
require(accounts.length == escrowBalances.length, "Number of accounts and balances don't match");
require(accounts.length == vestedBalances.length, "Number of accounts and vestedBalances don't match");
for (uint i = 0; i < accounts.length; i++) {
address account = accounts[i];
uint escrowedAmount = escrowBalances[i];
uint vestedAmount = vestedBalances[i];
// ensure account doesn't have escrow migration pending / being imported more than once
require(totalBalancePendingMigration[account] == 0, "Account migration is pending already");
/* Update totalEscrowedBalance for tracking the Synthetix balance of this contract. */
totalEscrowedBalance = totalEscrowedBalance.add(escrowedAmount);
/* Update totalEscrowedAccountBalance and totalVestedAccountBalance for each account */
totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(escrowedAmount);
totalVestedAccountBalance[account] = totalVestedAccountBalance[account].add(vestedAmount);
/* update totalBalancePendingMigration for account */
totalBalancePendingMigration[account] = escrowedAmount;
emit MigratedAccountEscrow(account, escrowedAmount, vestedAmount, now);
}
}
/* Internal function to add entry to vestingSchedules and emit event */
function _importVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal {
/* add vesting entry to account and assign an entryID to it */
uint entryID = BaseRewardEscrowV2._addVestingEntry(account, entry);
emit ImportedVestingEntry(account, entryID, entry.escrowAmount, entry.endTime);
}
/* ========== L2 MIGRATION ========== */
function burnForMigration(address account, uint[] calldata entryIDs)
external
onlySynthetixBridge
returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries)
{
require(entryIDs.length > 0, "Entry IDs required");
vestingEntries = new VestingEntries.VestingEntry[](entryIDs.length);
for (uint i = 0; i < entryIDs.length; i++) {
VestingEntries.VestingEntry storage entry = vestingSchedules[account][entryIDs[i]];
if (entry.escrowAmount > 0) {
vestingEntries[i] = entry;
/* add the escrow amount to escrowedAccountBalance */
escrowedAccountBalance = escrowedAccountBalance.add(entry.escrowAmount);
/* Delete the vesting entry being migrated */
delete vestingSchedules[account][entryIDs[i]];
}
}
/**
* update account total escrow balances for migration
* transfer the escrowed SNX being migrated to the L2 deposit contract
*/
if (escrowedAccountBalance > 0) {
_reduceAccountEscrowBalances(account, escrowedAccountBalance);
IERC20(address(synthetix())).transfer(synthetixBridgeToOptimism(), escrowedAccountBalance);
}
emit BurnedForMigrationToL2(account, entryIDs, escrowedAccountBalance, block.timestamp);
return (escrowedAccountBalance, vestingEntries);
}
/* ========== MODIFIERS ========== */
modifier onlySynthetixBridge() {
require(msg.sender == synthetixBridgeToOptimism(), "Can only be invoked by SynthetixBridgeToOptimism contract");
_;
}
modifier systemActive() {
systemStatus().requireSystemActive();
_;
}
/* ========== EVENTS ========== */
event MigratedAccountEscrow(address indexed account, uint escrowedAmount, uint vestedAmount, uint time);
event ImportedVestingSchedule(address indexed account, uint time, uint escrowAmount);
event BurnedForMigrationToL2(address indexed account, uint[] entryIDs, uint escrowedAmountMigrated, uint time);
event ImportedVestingEntry(address indexed account, uint entryID, uint escrowAmount, uint endTime);
event MigrateEntriesThresholdAmountUpdated(uint newAmount);
}
|
Internal function to add entry to vestingSchedules and emit event /
|
function _importVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal {
uint entryID = BaseRewardEscrowV2._addVestingEntry(account, entry);
emit ImportedVestingEntry(account, entryID, entry.escrowAmount, entry.endTime);
| 1,819,927 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns(uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract EthToSmthSwaps {
using SafeMath for uint;
address public owner;
address public ratingContractAddress;
uint256 SafeTime = 1 hours; // atomic swap timeOut
struct Swap {
address targetWallet;
bytes32 secret;
bytes20 secretHash;
uint256 createdAt;
uint256 balance;
}
// ETH Owner => BTC Owner => Swap
mapping(address => mapping(address => Swap)) public swaps;
mapping(address => mapping(address => uint)) public participantSigns;
constructor () public {
owner = msg.sender;
}
event CreateSwap(address _buyer, address _seller, uint256 _value, bytes20 _secretHash, uint256 createdAt);
// ETH Owner creates Swap with secretHash
// ETH Owner make token deposit
function createSwap(bytes20 _secretHash, address _participantAddress) public payable {
require(msg.value > 0);
require(swaps[msg.sender][_participantAddress].balance == uint256(0));
swaps[msg.sender][_participantAddress] = Swap(
_participantAddress,
bytes32(0),
_secretHash,
now,
msg.value
);
CreateSwap(_participantAddress, msg.sender, msg.value, _secretHash, now);
}
// ETH Owner creates Swap with secretHash
// ETH Owner make token deposit
function createSwapTarget(bytes20 _secretHash, address _participantAddress, address _targetWallet) public payable {
require(msg.value > 0);
require(swaps[msg.sender][_participantAddress].balance == uint256(0));
swaps[msg.sender][_participantAddress] = Swap(
_targetWallet,
bytes32(0),
_secretHash,
now,
msg.value
);
CreateSwap(_participantAddress, msg.sender, msg.value, _secretHash, now);
}
function getBalance(address _ownerAddress) public view returns (uint256) {
return swaps[_ownerAddress][msg.sender].balance;
}
// Get target wallet (buyer check)
function getTargetWallet(address _ownerAddress) public returns (address) {
return swaps[_ownerAddress][msg.sender].targetWallet;
}
event Withdraw(address _buyer, address _seller, uint256 withdrawnAt);
// BTC Owner withdraw money and adds secret key to swap
// BTC Owner receive +1 reputation
function withdraw(bytes32 _secret, address _ownerAddress) public {
Swap memory swap = swaps[_ownerAddress][msg.sender];
require(swap.secretHash == ripemd160(_secret));
require(swap.balance > uint256(0));
require(swap.createdAt.add(SafeTime) > now);
swap.targetWallet.transfer(swap.balance);
swaps[_ownerAddress][msg.sender].balance = 0;
swaps[_ownerAddress][msg.sender].secret = _secret;
Withdraw(msg.sender, _ownerAddress, now);
}
// BTC Owner withdraw money and adds secret key to swap
// BTC Owner receive +1 reputation
function withdrawNoMoney(bytes32 _secret, address participantAddress) public {
Swap memory swap = swaps[msg.sender][participantAddress];
require(swap.secretHash == ripemd160(_secret));
require(swap.balance > uint256(0));
require(swap.createdAt.add(SafeTime) > now);
swap.targetWallet.transfer(swap.balance);
swaps[msg.sender][participantAddress].balance = 0;
swaps[msg.sender][participantAddress].secret = _secret;
Withdraw(participantAddress, msg.sender, now);
}
// BTC Owner withdraw money and adds secret key to swap
// BTC Owner receive +1 reputation
function withdrawOther(bytes32 _secret, address _ownerAddress, address participantAddress) public {
Swap memory swap = swaps[_ownerAddress][participantAddress];
require(swap.secretHash == ripemd160(_secret));
require(swap.balance > uint256(0));
require(swap.createdAt.add(SafeTime) > now);
swap.targetWallet.transfer(swap.balance);
swaps[_ownerAddress][participantAddress].balance = 0;
swaps[_ownerAddress][participantAddress].secret = _secret;
Withdraw(participantAddress, _ownerAddress, now);
}
// ETH Owner receive secret
function getSecret(address _participantAddress) public view returns (bytes32) {
return swaps[msg.sender][_participantAddress].secret;
}
event Close(address _buyer, address _seller);
event Refund(address _buyer, address _seller);
// ETH Owner refund money
// BTC Owner gets -1 reputation
function refund(address _participantAddress) public {
Swap memory swap = swaps[msg.sender][_participantAddress];
require(swap.balance > uint256(0));
require(swap.createdAt.add(SafeTime) < now);
msg.sender.transfer(swap.balance);
clean(msg.sender, _participantAddress);
Refund(_participantAddress, msg.sender);
}
function clean(address _ownerAddress, address _participantAddress) internal {
delete swaps[_ownerAddress][_participantAddress];
delete participantSigns[_ownerAddress][_participantAddress];
}
}
|
BTC Owner withdraw money and adds secret key to swap BTC Owner receive +1 reputation
|
function withdraw(bytes32 _secret, address _ownerAddress) public {
Swap memory swap = swaps[_ownerAddress][msg.sender];
require(swap.secretHash == ripemd160(_secret));
require(swap.balance > uint256(0));
require(swap.createdAt.add(SafeTime) > now);
swap.targetWallet.transfer(swap.balance);
swaps[_ownerAddress][msg.sender].balance = 0;
swaps[_ownerAddress][msg.sender].secret = _secret;
Withdraw(msg.sender, _ownerAddress, now);
}
| 5,509,609 |
/**
*Submitted for verification at Etherscan.io on 2021-11-01
*/
// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [////IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* ////IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
////import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
////import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity 0.6.12;
interface IETHGateway {
function withdrawETH(uint256 amount, address onBehalfOf, bool redeemType, uint256 _cEthBal) external;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity 0.6.12;
interface ICEth {
function mint() external payable;
function exchangeRateCurrent() external returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function redeem(uint) external returns (uint);
function redeemUnderlying(uint) external returns (uint);
function exchangeRateStored() external view returns (uint);
function setExchangeRateStored(uint256 rate) external;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
////import "../utils/ContextUpgradeable.sol";
////import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* ////IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity 0.6.12;
interface IJCompoundHelper {
// function sendErc20ToCompoundHelper(address _underToken, address _cToken, uint256 _numTokensToSupply) external returns(uint256);
// function redeemCErc20TokensHelper(address _cToken, uint256 _amount, bool _redeemType) external returns (uint256 redeemResult);
function getMantissaHelper(uint256 _underDecs, uint256 _cTokenDecs) external pure returns (uint256 mantissa);
function getCompoundPurePriceHelper(address _cTokenAddress) external view returns (uint256 compoundPrice);
function getCompoundPriceHelper(address _cTokenAddress, uint256 _underDecs, uint256 _cTokenDecs) external view returns (uint256 compNormPrice);
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-06-18
* @summary: Markets Interface
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
interface IIncentivesController {
function trancheANewEnter(address account, address trancheA) external;
function trancheBNewEnter(address account, address trancheB) external;
function claimRewardsAllMarkets(address _account) external returns (bool);
function claimRewardSingleMarketTrA(uint256 _idxMarket, address _account) external;
function claimRewardSingleMarketTrB(uint256 _idxMarket, address _account) external;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity 0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferETHHelper {
function safeTransferETH(address _to, uint256 _value) internal {
(bool success,) = _to.call{value:_value}(new bytes(0));
require(success, 'TH ETH_TRANSFER_FAILED');
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-01-16
* @summary: Jibrel Protocol Storage
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
////import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
////import "./interfaces/ICEth.sol";
////import "./interfaces/IETHGateway.sol";
contract JCompoundStorage is OwnableUpgradeable {
/* WARNING: NEVER RE-ORDER VARIABLES! Always double-check that new variables are added APPEND-ONLY. Re-ordering variables can permanently BREAK the deployed proxy contract.*/
uint256 public constant PERCENT_DIVIDER = 10000; // percentage divider for redemption
struct TrancheAddresses {
address buyerCoinAddress; // ETH (ZERO_ADDRESS) or DAI
address cTokenAddress; // cETH or cDAI
address ATrancheAddress;
address BTrancheAddress;
}
struct TrancheParameters {
uint256 trancheAFixedPercentage; // fixed percentage (i.e. 4% = 0.04 * 10^18 = 40000000000000000)
uint256 trancheALastActionBlock;
uint256 storedTrancheAPrice;
uint256 trancheACurrentRPB;
uint16 redemptionPercentage; // percentage with 2 decimals (divided by 10000, i.e. 95% is 9500)
uint8 cTokenDecimals;
uint8 underlyingDecimals;
}
address public adminToolsAddress;
address public feesCollectorAddress;
address public tranchesDeployerAddress;
address public compTokenAddress;
address public comptrollerAddress;
address public rewardsToken;
uint256 public tranchePairsCounter;
uint256 public totalBlocksPerYear;
uint32 public redeemTimeout;
mapping(address => address) public cTokenContracts;
mapping(uint256 => TrancheAddresses) public trancheAddresses;
mapping(uint256 => TrancheParameters) public trancheParameters;
// last block number when the user buy/reddem tranche tokens
mapping(address => uint256) public lastActivity;
ICEth public cEthToken;
IETHGateway public ethGateway;
// enabling / disabling tranches for fund deposit
mapping(uint256 => bool) public trancheDepositEnabled;
}
contract JCompoundStorageV2 is JCompoundStorage {
struct StakingDetails {
uint256 startTime;
uint256 amount;
}
address public incentivesControllerAddress;
// user => trancheNum => counter
mapping (address => mapping(uint256 => uint256)) public stakeCounterTrA;
mapping (address => mapping(uint256 => uint256)) public stakeCounterTrB;
// user => trancheNum => stakeCounter => struct
mapping (address => mapping (uint256 => mapping (uint256 => StakingDetails))) public stakingDetailsTrancheA;
mapping (address => mapping (uint256 => mapping (uint256 => StakingDetails))) public stakingDetailsTrancheB;
address public jCompoundHelperAddress;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity 0.6.12;
interface IComptrollerLensInterface {
function claimComp(address) external;
function compAccrued(address) external view returns (uint);
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity 0.6.12;
interface ICErc20 {
function mint(uint256) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function redeem(uint) external returns (uint);
function redeemUnderlying(uint) external returns (uint);
function exchangeRateStored() external view returns (uint);
function setExchangeRateStored(uint256 rate) external;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity 0.6.12;
interface IJCompound {
event TrancheAddedToProtocol(uint256 trancheNum, address trancheA, address trancheB);
event TrancheATokenMinted(uint256 trancheNum, address buyer, uint256 amount, uint256 taAmount);
event TrancheBTokenMinted(uint256 trancheNum, address buyer, uint256 amount, uint256 tbAmount);
event TrancheATokenRedemption(uint256 trancheNum, address burner, uint256 amount, uint256 userAmount, uint256 feesAmount);
event TrancheBTokenRedemption(uint256 trancheNum, address burner, uint256 amount, uint256 userAmount, uint256 feesAmount);
function getSingleTrancheUserStakeCounterTrA(address _user, uint256 _trancheNum) external view returns (uint256);
function getSingleTrancheUserStakeCounterTrB(address _user, uint256 _trancheNum) external view returns (uint256);
function getSingleTrancheUserSingleStakeDetailsTrA(address _user, uint256 _trancheNum, uint256 _num) external view returns (uint256, uint256);
function getSingleTrancheUserSingleStakeDetailsTrB(address _user, uint256 _trancheNum, uint256 _num) external view returns (uint256, uint256);
function getTrAValue(uint256 _trancheNum) external view returns (uint256 trANormValue);
function getTrBValue(uint256 _trancheNum) external view returns (uint256);
function getTotalValue(uint256 _trancheNum) external view returns (uint256);
function getTrancheACurrentRPB(uint256 _trancheNum) external view returns (uint256);
function getTrancheAExchangeRate(uint256 _trancheNum) external view returns (uint256);
function getTrancheBExchangeRate(uint256 _trancheNum, uint256 _newAmount) external view returns (uint256 tbPrice);
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-01-15
* @summary: JProtocol Interface
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
interface IJTranchesDeployer {
function deployNewTrancheATokens(string calldata _nameA, string calldata _symbolA, address _sender, address _rewardToken) external returns (address);
function deployNewTrancheBTokens(string calldata _nameB, string calldata _symbolB, address _sender, address _rewardToken) external returns (address);
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-01-16
* @summary: JTranches Interface
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
interface IJTrancheTokens {
function mint(address account, uint256 value) external;
function burn(uint256 value) external;
function updateFundsReceived() external;
function emergencyTokenTransfer(address _token, address _to, uint256 _amount) external;
function setRewardTokenAddress(address _token) external;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-05-16
* @summary: Admin Tools Interface
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
interface IJAdminTools {
function isAdmin(address account) external view returns (bool);
function addAdmin(address account) external;
function removeAdmin(address account) external;
function renounceAdmin() external;
event AdminAdded(address account);
event AdminRemoved(address account);
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
////import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and 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;
}
uint256[49] private __gap;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
////import "./IERC20Upgradeable.sol";
////import "../../math/SafeMathUpgradeable.sol";
////import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JCompound.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-02-11
* @summary: Jibrel Compound Tranche Protocol
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
////import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
////import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
////import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
////import "./interfaces/IJAdminTools.sol";
////import "./interfaces/IJTrancheTokens.sol";
////import "./interfaces/IJTranchesDeployer.sol";
////import "./interfaces/IJCompound.sol";
////import "./interfaces/ICErc20.sol";
////import "./interfaces/IComptrollerLensInterface.sol";
////import "./JCompoundStorage.sol";
////import "./TransferETHHelper.sol";
////import "./interfaces/IIncentivesController.sol";
////import "./interfaces/IJCompoundHelper.sol";
contract JCompound is OwnableUpgradeable, ReentrancyGuardUpgradeable, JCompoundStorageV2, IJCompound {
using SafeMathUpgradeable for uint256;
/**
* @dev contract initializer
* @param _adminTools price oracle address
* @param _feesCollector fees collector contract address
* @param _tranchesDepl tranches deployer contract address
* @param _compTokenAddress COMP token contract address
* @param _comptrollAddress comptroller contract address
* @param _rewardsToken rewards token address (slice token address)
*/
function initialize(address _adminTools,
address _feesCollector,
address _tranchesDepl,
address _compTokenAddress,
address _comptrollAddress,
address _rewardsToken) external initializer() {
OwnableUpgradeable.__Ownable_init();
adminToolsAddress = _adminTools;
feesCollectorAddress = _feesCollector;
tranchesDeployerAddress = _tranchesDepl;
compTokenAddress = _compTokenAddress;
comptrollerAddress = _comptrollAddress;
rewardsToken = _rewardsToken;
redeemTimeout = 3; //default
totalBlocksPerYear = 2102400; // same number like in Compound protocol
}
/**
* @dev set constants for JCompound
* @param _trNum tranche number
* @param _redemPerc redemption percentage (scaled by 1e4)
* @param _redemTimeout redemption timeout, in blocks
* @param _blocksPerYear blocks per year (compound set it to 2102400)
*/
function setConstantsValues(uint256 _trNum, uint16 _redemPerc, uint32 _redemTimeout, uint256 _blocksPerYear) external onlyAdmins {
trancheParameters[_trNum].redemptionPercentage = _redemPerc;
redeemTimeout = _redemTimeout;
totalBlocksPerYear = _blocksPerYear;
}
/**
* @dev set eth gateway
* @param _ethGateway ethGateway address
*/
function setETHGateway(address _ethGateway) external onlyAdmins {
ethGateway = IETHGateway(_ethGateway);
}
/**
* @dev set incentive rewards address
* @param _incentivesController incentives controller contract address
*/
function setincentivesControllerAddress(address _incentivesController) external onlyAdmins {
incentivesControllerAddress = _incentivesController;
}
/**
* @dev set incentive rewards address
* @param _helper JCompound helper contract address
*/
function setJCompoundHelperAddress(address _helper) external onlyAdmins {
jCompoundHelperAddress = _helper;
}
/**
* @dev admins modifiers
*/
modifier onlyAdmins() {
require(IJAdminTools(adminToolsAddress).isAdmin(msg.sender), "!Admin");
_;
}
// This is needed to receive ETH
fallback() external payable {}
receive() external payable {}
/**
* @dev set new addresses for price oracle, fees collector and tranche deployer
* @param _adminTools price oracle address
* @param _feesCollector fees collector contract address
* @param _tranchesDepl tranches deployer contract address
* @param _compTokenAddress COMP token contract address
* @param _comptrollAddress comptroller contract address
* @param _rewardsToken rewards token address (slice token address)
*/
function setNewEnvironment(address _adminTools,
address _feesCollector,
address _tranchesDepl,
address _compTokenAddress,
address _comptrollAddress,
address _rewardsToken) external onlyOwner {
require((_adminTools != address(0)) && (_feesCollector != address(0)) &&
(_tranchesDepl != address(0)) && (_comptrollAddress != address(0)) && (_compTokenAddress != address(0)), "ChkAddress");
adminToolsAddress = _adminTools;
feesCollectorAddress = _feesCollector;
tranchesDeployerAddress = _tranchesDepl;
compTokenAddress = _compTokenAddress;
comptrollerAddress = _comptrollAddress;
rewardsToken = _rewardsToken;
}
/**
* @dev set relationship between ethers and the corresponding Compound cETH contract
* @param _cEtherContract compound token contract address (cETH contract, on Kovan: 0x41b5844f4680a8c38fbb695b7f9cfd1f64474a72)
*/
function setCEtherContract(address _cEtherContract) external onlyAdmins {
cEthToken = ICEth(_cEtherContract);
cTokenContracts[address(0)] = _cEtherContract;
}
/**
* @dev set relationship between a token and the corresponding Compound cToken contract
* @param _erc20Contract token contract address (i.e. DAI contract, on Kovan: 0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa)
* @param _cErc20Contract compound token contract address (i.e. cDAI contract, on Kovan: 0xf0d0eb522cfa50b716b3b1604c4f0fa6f04376ad)
*/
function setCTokenContract(address _erc20Contract, address _cErc20Contract) external onlyAdmins {
cTokenContracts[_erc20Contract] = _cErc20Contract;
}
/**
* @dev check if a cToken is allowed or not
* @param _erc20Contract token contract address (i.e. DAI contract, on Kovan: 0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa)
* @return true or false
*/
function isCTokenAllowed(address _erc20Contract) public view returns (bool) {
return cTokenContracts[_erc20Contract] != address(0);
}
/**
* @dev get RPB from compound
* @param _trancheNum tranche number
* @return cToken compound supply RPB
*/
function getCompoundSupplyRPB(uint256 _trancheNum) external view returns (uint256) {
ICErc20 cToken = ICErc20(cTokenContracts[trancheAddresses[_trancheNum].buyerCoinAddress]);
return cToken.supplyRatePerBlock();
}
/**
* @dev check if a cToken is allowed or not
* @param _trancheNum tranche number
* @param _cTokenDec cToken decimals
* @param _underlyingDec underlying token decimals
*/
function setDecimals(uint256 _trancheNum, uint8 _cTokenDec, uint8 _underlyingDec) external onlyAdmins {
require((_cTokenDec <= 18) && (_underlyingDec <= 18), "Decs");
trancheParameters[_trancheNum].cTokenDecimals = _cTokenDec;
trancheParameters[_trancheNum].underlyingDecimals = _underlyingDec;
}
/**
* @dev set tranche A fixed percentage (scaled by 1e18)
* @param _trancheNum tranche number
* @param _newTrAPercentage new tranche A fixed percentage (scaled by 1e18)
*/
function setTrancheAFixedPercentage(uint256 _trancheNum, uint256 _newTrAPercentage) external onlyAdmins {
trancheParameters[_trancheNum].trancheAFixedPercentage = _newTrAPercentage;
trancheParameters[_trancheNum].storedTrancheAPrice = setTrancheAExchangeRate(_trancheNum);
}
/**
* @dev add tranche in protocol
* @param _erc20Contract token contract address (0x0000000000000000000000000000000000000000 if eth)
* @param _nameA tranche A token name
* @param _symbolA tranche A token symbol
* @param _nameB tranche B token name
* @param _symbolB tranche B token symbol
* @param _fixedRpb tranche A percentage fixed compounded interest per year
* @param _cTokenDec cToken decimals
* @param _underlyingDec underlying token decimals
*/
function addTrancheToProtocol(address _erc20Contract, string memory _nameA, string memory _symbolA, string memory _nameB,
string memory _symbolB, uint256 _fixedRpb, uint8 _cTokenDec, uint8 _underlyingDec) external onlyAdmins nonReentrant {
require(tranchesDeployerAddress != address(0), "!TrDepl");
require(isCTokenAllowed(_erc20Contract), "!Allow");
trancheAddresses[tranchePairsCounter].buyerCoinAddress = _erc20Contract;
trancheAddresses[tranchePairsCounter].cTokenAddress = cTokenContracts[_erc20Contract];
// our tokens always with 18 decimals
trancheAddresses[tranchePairsCounter].ATrancheAddress =
IJTranchesDeployer(tranchesDeployerAddress).deployNewTrancheATokens(_nameA, _symbolA, msg.sender, rewardsToken);
trancheAddresses[tranchePairsCounter].BTrancheAddress =
IJTranchesDeployer(tranchesDeployerAddress).deployNewTrancheBTokens(_nameB, _symbolB, msg.sender, rewardsToken);
trancheParameters[tranchePairsCounter].cTokenDecimals = _cTokenDec;
trancheParameters[tranchePairsCounter].underlyingDecimals = _underlyingDec;
trancheParameters[tranchePairsCounter].trancheAFixedPercentage = _fixedRpb;
trancheParameters[tranchePairsCounter].trancheALastActionBlock = block.number;
// if we would like to have always 18 decimals
trancheParameters[tranchePairsCounter].storedTrancheAPrice =
IJCompoundHelper(jCompoundHelperAddress).getCompoundPriceHelper(cTokenContracts[_erc20Contract], _underlyingDec, _cTokenDec);
trancheParameters[tranchePairsCounter].redemptionPercentage = 9950; //default value 99.5%
calcRPBFromPercentage(tranchePairsCounter); // initialize tranche A RPB
emit TrancheAddedToProtocol(tranchePairsCounter, trancheAddresses[tranchePairsCounter].ATrancheAddress, trancheAddresses[tranchePairsCounter].BTrancheAddress);
tranchePairsCounter = tranchePairsCounter.add(1);
}
/**
* @dev enables or disables tranche deposit (default: disabled)
* @param _trancheNum tranche number
* @param _enable true or false
*/
function setTrancheDeposit(uint256 _trancheNum, bool _enable) external onlyAdmins {
trancheDepositEnabled[_trancheNum] = _enable;
}
/**
* @dev send an amount of tokens to corresponding compound contract (it takes tokens from this contract). Only allowed token should be sent
* @param _erc20Contract token contract address
* @param _numTokensToSupply token amount to be sent
* @return mint result
*/
function sendErc20ToCompound(address _erc20Contract, uint256 _numTokensToSupply) internal returns(uint256) {
address cTokenAddress = cTokenContracts[_erc20Contract];
require(cTokenAddress != address(0), "!Accept");
IERC20Upgradeable underlying = IERC20Upgradeable(_erc20Contract);
ICErc20 cToken = ICErc20(cTokenAddress);
SafeERC20Upgradeable.safeApprove(underlying, cTokenAddress, _numTokensToSupply);
require(underlying.allowance(address(this), cTokenAddress) >= _numTokensToSupply, "!AllowCToken");
uint256 mintResult = cToken.mint(_numTokensToSupply);
return mintResult;
}
/**
* @dev redeem an amount of cTokens to have back original tokens (tokens remains in this contract). Only allowed token should be sent
* @param _erc20Contract original token contract address
* @param _amount cToken amount to be sent
* @param _redeemType true or false, normally true
*/
function redeemCErc20Tokens(address _erc20Contract, uint256 _amount, bool _redeemType) internal returns (uint256 redeemResult) {
address cTokenAddress = cTokenContracts[_erc20Contract];
require(cTokenAddress != address(0), "!Accept");
ICErc20 cToken = ICErc20(cTokenAddress);
if (_redeemType) {
// Retrieve your asset based on a cToken amount
redeemResult = cToken.redeem(_amount);
} else {
// Retrieve your asset based on an amount of the asset
redeemResult = cToken.redeemUnderlying(_amount);
}
return redeemResult;
}
/**
* @dev get Tranche A exchange rate
* @param _trancheNum tranche number
* @return tranche A token stored price
*/
function getTrancheAExchangeRate(uint256 _trancheNum) public view override returns (uint256) {
return trancheParameters[_trancheNum].storedTrancheAPrice;
}
/**
* @dev get RPB for a given percentage (expressed in 1e18)
* @param _trancheNum tranche number
* @return RPB for a fixed percentage
*/
function getTrancheACurrentRPB(uint256 _trancheNum) external view override returns (uint256) {
return trancheParameters[_trancheNum].trancheACurrentRPB;
}
/**
* @dev set Tranche A exchange rate
* @param _trancheNum tranche number
* @return tranche A token stored price
*/
function setTrancheAExchangeRate(uint256 _trancheNum) internal returns (uint256) {
calcRPBFromPercentage(_trancheNum);
uint256 deltaBlocks = (block.number).sub(trancheParameters[_trancheNum].trancheALastActionBlock);
if (deltaBlocks > 0) {
uint256 deltaPrice = (trancheParameters[_trancheNum].trancheACurrentRPB).mul(deltaBlocks);
trancheParameters[_trancheNum].storedTrancheAPrice = (trancheParameters[_trancheNum].storedTrancheAPrice).add(deltaPrice);
trancheParameters[_trancheNum].trancheALastActionBlock = block.number;
}
return trancheParameters[_trancheNum].storedTrancheAPrice;
}
/**
* @dev get Tranche A exchange rate (tokens with 18 decimals)
* @param _trancheNum tranche number
* @return tranche A token current price
*/
function calcRPBFromPercentage(uint256 _trancheNum) public returns (uint256) {
// if normalized price in tranche A price, everything should be scaled to 1e18
trancheParameters[_trancheNum].trancheACurrentRPB = trancheParameters[_trancheNum].storedTrancheAPrice
.mul(trancheParameters[_trancheNum].trancheAFixedPercentage).div(totalBlocksPerYear).div(1e18);
return trancheParameters[_trancheNum].trancheACurrentRPB;
}
/**
* @dev get Tranche A value in underlying tokens
* @param _trancheNum tranche number
* @return trANormValue tranche A value in underlying tokens
*/
function getTrAValue(uint256 _trancheNum) public view override returns (uint256 trANormValue) {
uint256 totASupply = IERC20Upgradeable(trancheAddresses[_trancheNum].ATrancheAddress).totalSupply();
uint256 diffDec = uint256(18).sub(uint256(trancheParameters[_trancheNum].underlyingDecimals));
uint256 storedAPrice = trancheParameters[_trancheNum].storedTrancheAPrice;
trANormValue = totASupply.mul(storedAPrice).div(1e18).div(10 ** diffDec);
return trANormValue;
}
/**
* @dev get Tranche B value in underlying tokens
* @param _trancheNum tranche number
* @return tranche B valuein underlying tokens
*/
function getTrBValue(uint256 _trancheNum) external view override returns (uint256) {
uint256 totProtValue = getTotalValue(_trancheNum);
uint256 totTrAValue = getTrAValue(_trancheNum);
if (totProtValue > totTrAValue) {
return totProtValue.sub(totTrAValue);
} else
return 0;
}
/**
* @dev get Tranche total value in underlying tokens
* @param _trancheNum tranche number
* @return tranche total value in underlying tokens
*/
function getTotalValue(uint256 _trancheNum) public view override returns (uint256) {
address cTokenAddress = trancheAddresses[_trancheNum].cTokenAddress;
uint256 underDecs = uint256(trancheParameters[_trancheNum].underlyingDecimals);
uint256 cTokenDecs = uint256(trancheParameters[_trancheNum].cTokenDecimals);
uint256 compNormPrice = IJCompoundHelper(jCompoundHelperAddress).getCompoundPriceHelper(cTokenAddress, underDecs, cTokenDecs);
uint256 mantissa = IJCompoundHelper(jCompoundHelperAddress).getMantissaHelper(underDecs, cTokenDecs);
if (mantissa < 18) {
compNormPrice = compNormPrice.div(10 ** (uint256(18).sub(mantissa)));
} else {
compNormPrice = IJCompoundHelper(jCompoundHelperAddress).getCompoundPurePriceHelper(cTokenAddress);
}
uint256 totProtSupply = getTokenBalance(trancheAddresses[_trancheNum].cTokenAddress);
return totProtSupply.mul(compNormPrice).div(1e18);
}
/**
* @dev get Tranche B exchange rate
* @param _trancheNum tranche number
* @param _newAmount new amount entering tranche B (in underlying tokens)
* @return tbPrice tranche B token current price
*/
function getTrancheBExchangeRate(uint256 _trancheNum, uint256 _newAmount) public view override returns (uint256 tbPrice) {
// set amount of tokens to be minted via taToken price
// Current tbDai price = (((cDai X cPrice)-(aSupply X taPrice)) / bSupply)
// where: cDai = How much cDai we hold in the protocol
// cPrice = cDai / Dai price
// aSupply = Total number of taDai in protocol
// taPrice = taDai / Dai price
// bSupply = Total number of tbDai in protocol
uint256 totTrBValue;
uint256 totBSupply = IERC20Upgradeable(trancheAddresses[_trancheNum].BTrancheAddress).totalSupply(); // 18 decimals
// if normalized price in tranche A price, everything should be scaled to 1e18
uint256 underlyingDec = uint256(trancheParameters[_trancheNum].underlyingDecimals);
uint256 normAmount = _newAmount;
if (underlyingDec < 18)
normAmount = _newAmount.mul(10 ** uint256(18).sub(underlyingDec));
uint256 newBSupply = totBSupply.add(normAmount); // 18 decimals
uint256 totProtValue = getTotalValue(_trancheNum).add(_newAmount); //underlying token decimals
uint256 totTrAValue = getTrAValue(_trancheNum); //underlying token decimals
if (totProtValue >= totTrAValue)
totTrBValue = totProtValue.sub(totTrAValue); //underlying token decimals
else
totTrBValue = 0;
// if normalized price in tranche A price, everything should be scaled to 1e18
if (underlyingDec < 18 && totTrBValue > 0) {
totTrBValue = totTrBValue.mul(10 ** (uint256(18).sub(underlyingDec)));
}
if (totTrBValue > 0 && newBSupply > 0) {
// if normalized price in tranche A price, everything should be scaled to 1e18
tbPrice = totTrBValue.mul(1e18).div(newBSupply);
} else
// if normalized price in tranche A price, everything should be scaled to 1e18
tbPrice = uint256(1e18);
return tbPrice;
}
/**
* @dev set staking details for tranche A holders, with number, amount and time
* @param _trancheNum tranche number
* @param _account user's account
* @param _stkNum staking detail counter
* @param _amount amount of tranche A tokens
* @param _time time to be considered the deposit
*/
function setTrAStakingDetails(uint256 _trancheNum, address _account, uint256 _stkNum, uint256 _amount, uint256 _time) external onlyAdmins {
stakeCounterTrA[_account][_trancheNum] = _stkNum;
StakingDetails storage details = stakingDetailsTrancheA[_account][_trancheNum][_stkNum];
details.startTime = _time;
details.amount = _amount;
}
/**
* @dev when redemption occurs on tranche A, removing tranche A tokens from staking information (FIFO logic)
* @param _trancheNum tranche number
* @param _amount amount of redeemed tokens
*/
function decreaseTrancheATokenFromStake(uint256 _trancheNum, uint256 _amount) internal {
uint256 senderCounter = stakeCounterTrA[msg.sender][_trancheNum];
uint256 tmpAmount = _amount;
for (uint i = 1; i <= senderCounter; i++) {
StakingDetails storage details = stakingDetailsTrancheA[msg.sender][_trancheNum][i];
if (details.amount > 0) {
if (details.amount <= tmpAmount) {
tmpAmount = tmpAmount.sub(details.amount);
details.amount = 0;
//delete stakingDetailsTrancheA[msg.sender][_trancheNum][i];
// update details number
//stakeCounterTrA[msg.sender][_trancheNum] = stakeCounterTrA[msg.sender][_trancheNum].sub(1);
} else {
details.amount = details.amount.sub(tmpAmount);
tmpAmount = 0;
}
}
if (tmpAmount == 0)
break;
}
}
function getSingleTrancheUserStakeCounterTrA(address _user, uint256 _trancheNum) external view override returns (uint256) {
return stakeCounterTrA[_user][_trancheNum];
}
function getSingleTrancheUserSingleStakeDetailsTrA(address _user, uint256 _trancheNum, uint256 _num) external view override returns (uint256, uint256) {
return (stakingDetailsTrancheA[_user][_trancheNum][_num].startTime, stakingDetailsTrancheA[_user][_trancheNum][_num].amount);
}
/**
* @dev set staking details for tranche B holders, with number, amount and time
* @param _trancheNum tranche number
* @param _account user's account
* @param _stkNum staking detail counter
* @param _amount amount of tranche B tokens
* @param _time time to be considered the deposit
*/
function setTrBStakingDetails(uint256 _trancheNum, address _account, uint256 _stkNum, uint256 _amount, uint256 _time) external onlyAdmins {
stakeCounterTrB[_account][_trancheNum] = _stkNum;
StakingDetails storage details = stakingDetailsTrancheB[_account][_trancheNum][_stkNum];
details.startTime = _time;
details.amount = _amount;
}
/**
* @dev when redemption occurs on tranche B, removing tranche B tokens from staking information (FIFO logic)
* @param _trancheNum tranche number
* @param _amount amount of redeemed tokens
*/
function decreaseTrancheBTokenFromStake(uint256 _trancheNum, uint256 _amount) internal {
uint256 senderCounter = stakeCounterTrB[msg.sender][_trancheNum];
uint256 tmpAmount = _amount;
for (uint i = 1; i <= senderCounter; i++) {
StakingDetails storage details = stakingDetailsTrancheB[msg.sender][_trancheNum][i];
if (details.amount > 0) {
if (details.amount <= tmpAmount) {
tmpAmount = tmpAmount.sub(details.amount);
details.amount = 0;
//delete stakingDetailsTrancheB[msg.sender][_trancheNum][i];
// update details number
//stakeCounterTrB[msg.sender][_trancheNum] = stakeCounterTrB[msg.sender][_trancheNum].sub(1);
} else {
details.amount = details.amount.sub(tmpAmount);
tmpAmount = 0;
}
}
if (tmpAmount == 0)
break;
}
}
function getSingleTrancheUserStakeCounterTrB(address _user, uint256 _trancheNum) external view override returns (uint256) {
return stakeCounterTrB[_user][_trancheNum];
}
function getSingleTrancheUserSingleStakeDetailsTrB(address _user, uint256 _trancheNum, uint256 _num) external view override returns (uint256, uint256) {
return (stakingDetailsTrancheB[_user][_trancheNum][_num].startTime, stakingDetailsTrancheB[_user][_trancheNum][_num].amount);
}
/**
* @dev buy Tranche A Tokens
* @param _trancheNum tranche number
* @param _amount amount of stable coins sent by buyer
*/
function buyTrancheAToken(uint256 _trancheNum, uint256 _amount) external payable nonReentrant {
require(trancheDepositEnabled[_trancheNum], "!Deposit");
address cTokenAddress = trancheAddresses[_trancheNum].cTokenAddress;
address underTokenAddress = trancheAddresses[_trancheNum].buyerCoinAddress;
uint256 prevCompTokenBalance = getTokenBalance(cTokenAddress);
if (underTokenAddress == address(0)){
require(msg.value == _amount, "!Amount");
//Transfer ETH from msg.sender to protocol;
TransferETHHelper.safeTransferETH(address(this), _amount);
// transfer ETH to Coompound receiving cETH
cEthToken.mint{value: _amount}();
} else {
// check approve
require(IERC20Upgradeable(underTokenAddress).allowance(msg.sender, address(this)) >= _amount, "!Allowance");
//Transfer DAI from msg.sender to protocol;
SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(underTokenAddress), msg.sender, address(this), _amount);
// transfer DAI to Coompound receiving cDai
sendErc20ToCompound(underTokenAddress, _amount);
// IJCompoundHelper(jCompoundHelperAddress).sendErc20ToCompoundHelper(underTokenAddress, cTokenAddress, _amount);
}
uint256 newCompTokenBalance = getTokenBalance(cTokenAddress);
// set amount of tokens to be minted calculate taToken amount via taToken price
setTrancheAExchangeRate(_trancheNum);
uint256 taAmount;
if (newCompTokenBalance > prevCompTokenBalance) {
// if normalized price in tranche A price, everything should be scaled to 1e18
uint256 diffDec = uint256(18).sub(uint256(trancheParameters[_trancheNum].underlyingDecimals));
uint256 normAmount = _amount.mul(10 ** diffDec);
taAmount = normAmount.mul(1e18).div(trancheParameters[_trancheNum].storedTrancheAPrice);
//Mint trancheA tokens and send them to msg.sender and notify to incentive controller BEFORE totalSupply updates
IIncentivesController(incentivesControllerAddress).trancheANewEnter(msg.sender, trancheAddresses[_trancheNum].ATrancheAddress);
IJTrancheTokens(trancheAddresses[_trancheNum].ATrancheAddress).mint(msg.sender, taAmount);
} else {
taAmount = 0;
}
stakeCounterTrA[msg.sender][_trancheNum] = stakeCounterTrA[msg.sender][_trancheNum].add(1);
StakingDetails storage details = stakingDetailsTrancheA[msg.sender][_trancheNum][stakeCounterTrA[msg.sender][_trancheNum]];
details.startTime = block.timestamp;
details.amount = taAmount;
lastActivity[msg.sender] = block.number;
emit TrancheATokenMinted(_trancheNum, msg.sender, _amount, taAmount);
}
/**
* @dev redeem Tranche A Tokens
* @param _trancheNum tranche number
* @param _amount amount of stable coins sent by buyer
*/
function redeemTrancheAToken(uint256 _trancheNum, uint256 _amount) external nonReentrant {
require((block.number).sub(lastActivity[msg.sender]) >= redeemTimeout, "!Timeout");
// check approve
address aTrancheAddress = trancheAddresses[_trancheNum].ATrancheAddress;
require(IERC20Upgradeable(aTrancheAddress).allowance(msg.sender, address(this)) >= _amount, "!Allowance");
//Transfer DAI from msg.sender to protocol;
SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(aTrancheAddress), msg.sender, address(this), _amount);
uint256 oldBal;
uint256 diffBal;
uint256 userAmount;
uint256 feesAmount;
setTrancheAExchangeRate(_trancheNum);
// if normalized price in tranche A price, everything should be scaled to 1e18
uint256 taAmount = _amount.mul(trancheParameters[_trancheNum].storedTrancheAPrice).div(1e18);
uint256 diffDec = uint256(18).sub(uint256(trancheParameters[_trancheNum].underlyingDecimals));
uint256 normAmount = taAmount.div(10 ** diffDec);
address cTokenAddress = trancheAddresses[_trancheNum].cTokenAddress;
uint256 cTokenBal = getTokenBalance(cTokenAddress); // needed for emergency
address underTokenAddress = trancheAddresses[_trancheNum].buyerCoinAddress;
uint256 redeemPerc = uint256(trancheParameters[_trancheNum].redemptionPercentage);
if (underTokenAddress == address(0)) {
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(cTokenAddress), address(ethGateway), cTokenBal);
// calculate taAmount via cETH price
oldBal = getEthBalance();
ethGateway.withdrawETH(normAmount, address(this), false, cTokenBal);
diffBal = getEthBalance().sub(oldBal);
userAmount = diffBal.mul(redeemPerc).div(PERCENT_DIVIDER);
TransferETHHelper.safeTransferETH(msg.sender, userAmount);
if (diffBal != userAmount) {
// transfer fees to JFeesCollector
feesAmount = diffBal.sub(userAmount);
TransferETHHelper.safeTransferETH(feesCollectorAddress, feesAmount);
}
} else {
// calculate taAmount via cToken price
oldBal = getTokenBalance(underTokenAddress);
uint256 compoundRetCode = redeemCErc20Tokens(underTokenAddress, normAmount, false);
// uint256 compoundRetCode = IJCompoundHelper(jCompoundHelperAddress).redeemCErc20TokensHelper(cTokenAddress, normAmount, false);
if(compoundRetCode != 0) {
// emergency: send all ctokens balance to compound
redeemCErc20Tokens(underTokenAddress, cTokenBal, true);
// SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(aTrancheAddress), jCompoundHelperAddress, cTokenBal);
// IJCompoundHelper(jCompoundHelperAddress).redeemCErc20TokensHelper(cTokenAddress, cTokenBal, false);
}
diffBal = getTokenBalance(underTokenAddress).sub(oldBal);
userAmount = diffBal.mul(redeemPerc).div(PERCENT_DIVIDER);
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(underTokenAddress), msg.sender, userAmount);
if (diffBal != userAmount) {
// transfer fees to JFeesCollector
feesAmount = diffBal.sub(userAmount);
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(underTokenAddress), feesCollectorAddress, feesAmount);
}
}
// claim and transfer rewards to msg.sender. Be sure to wait for this function to be completed!
bool rewClaimCompleted = IIncentivesController(incentivesControllerAddress).claimRewardsAllMarkets(msg.sender);
// decrease tokens after claiming rewards
if (rewClaimCompleted && _amount > 0)
decreaseTrancheATokenFromStake(_trancheNum, _amount);
IJTrancheTokens(aTrancheAddress).burn(_amount);
lastActivity[msg.sender] = block.number;
emit TrancheATokenRedemption(_trancheNum, msg.sender, 0, userAmount, feesAmount);
}
/**
* @dev buy Tranche B Tokens
* @param _trancheNum tranche number
* @param _amount amount of stable coins sent by buyer
*/
function buyTrancheBToken(uint256 _trancheNum, uint256 _amount) external payable nonReentrant {
require(trancheDepositEnabled[_trancheNum], "!Deposit");
address cTokenAddress = trancheAddresses[_trancheNum].cTokenAddress;
address underTokenAddress = trancheAddresses[_trancheNum].buyerCoinAddress;
uint256 prevCompTokenBalance = getTokenBalance(cTokenAddress);
// if eth, ignore _amount parameter and set it to msg.value
if (trancheAddresses[_trancheNum].buyerCoinAddress == address(0)) {
require(msg.value == _amount, "!Amount");
//_amount = msg.value;
}
// refresh value for tranche A
setTrancheAExchangeRate(_trancheNum);
// get tranche B exchange rate
// if normalized price in tranche B price, everything should be scaled to 1e18
uint256 diffDec = uint256(18).sub(uint256(trancheParameters[_trancheNum].underlyingDecimals));
uint256 normAmount = _amount.mul(10 ** diffDec);
uint256 tbAmount = normAmount.mul(1e18).div(getTrancheBExchangeRate(_trancheNum, _amount));
if (underTokenAddress == address(0)) {
TransferETHHelper.safeTransferETH(address(this), _amount);
// transfer ETH to Coompound receiving cETH
cEthToken.mint{value: _amount}();
} else {
// check approve
require(IERC20Upgradeable(underTokenAddress).allowance(msg.sender, address(this)) >= _amount, "!Allowance");
//Transfer DAI from msg.sender to protocol;
SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(underTokenAddress), msg.sender, address(this), _amount);
// transfer DAI to Couompound receiving cDai
sendErc20ToCompound(underTokenAddress, _amount);
// IJCompoundHelper(jCompoundHelperAddress).sendErc20ToCompoundHelper(underTokenAddress, cTokenAddress, _amount);
}
uint256 newCompTokenBalance = getTokenBalance(cTokenAddress);
if (newCompTokenBalance > prevCompTokenBalance) {
//Mint trancheB tokens and send them to msg.sender and notify to incentive controller BEFORE totalSupply updates
IIncentivesController(incentivesControllerAddress).trancheBNewEnter(msg.sender, trancheAddresses[_trancheNum].BTrancheAddress);
IJTrancheTokens(trancheAddresses[_trancheNum].BTrancheAddress).mint(msg.sender, tbAmount);
} else
tbAmount = 0;
stakeCounterTrB[msg.sender][_trancheNum] = stakeCounterTrB[msg.sender][_trancheNum].add(1);
StakingDetails storage details = stakingDetailsTrancheB[msg.sender][_trancheNum][stakeCounterTrB[msg.sender][_trancheNum]];
details.startTime = block.timestamp;
details.amount = tbAmount;
lastActivity[msg.sender] = block.number;
emit TrancheBTokenMinted(_trancheNum, msg.sender, _amount, tbAmount);
}
/**
* @dev redeem Tranche B Tokens
* @param _trancheNum tranche number
* @param _amount amount of stable coins sent by buyer
*/
function redeemTrancheBToken(uint256 _trancheNum, uint256 _amount) external nonReentrant {
require((block.number).sub(lastActivity[msg.sender]) >= redeemTimeout, "!Timeout");
// check approve
address bTrancheAddress = trancheAddresses[_trancheNum].BTrancheAddress;
require(IERC20Upgradeable(bTrancheAddress).allowance(msg.sender, address(this)) >= _amount, "!Allowance");
//Transfer DAI from msg.sender to protocol;
SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(bTrancheAddress), msg.sender, address(this), _amount);
uint256 oldBal;
uint256 diffBal;
uint256 userAmount;
uint256 feesAmount;
// refresh value for tranche A
setTrancheAExchangeRate(_trancheNum);
// get tranche B exchange rate
// if normalized price in tranche B price, everything should be scaled to 1e18
uint256 tbAmount = _amount.mul(getTrancheBExchangeRate(_trancheNum, 0)).div(1e18);
uint256 diffDec = uint256(18).sub(uint256(trancheParameters[_trancheNum].underlyingDecimals));
uint256 normAmount = tbAmount.div(10 ** diffDec);
address cTokenAddress = trancheAddresses[_trancheNum].cTokenAddress;
uint256 cTokenBal = getTokenBalance(cTokenAddress); // needed for emergency
address underTokenAddress = trancheAddresses[_trancheNum].buyerCoinAddress;
uint256 redeemPerc = uint256(trancheParameters[_trancheNum].redemptionPercentage);
if (underTokenAddress == address(0)){
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(cTokenAddress), address(ethGateway), cTokenBal);
// calculate tbETH amount via cETH price
oldBal = getEthBalance();
ethGateway.withdrawETH(normAmount, address(this), false, cTokenBal);
diffBal = getEthBalance().sub(oldBal);
userAmount = diffBal.mul(redeemPerc).div(PERCENT_DIVIDER);
TransferETHHelper.safeTransferETH(msg.sender, userAmount);
if (diffBal != userAmount) {
// transfer fees to JFeesCollector
feesAmount = diffBal.sub(userAmount);
TransferETHHelper.safeTransferETH(feesCollectorAddress, feesAmount);
}
} else {
// calculate taToken amount via cToken price
oldBal = getTokenBalance(underTokenAddress);
require(redeemCErc20Tokens(underTokenAddress, normAmount, false) == 0, "!cTokenAnswer");
// uint256 compRetCode = IJCompoundHelper(jCompoundHelperAddress).redeemCErc20TokensHelper(cTokenAddress, normAmount, false);
// require(compRetCode == 0, "!cTokenAnswer");
diffBal = getTokenBalance(underTokenAddress);
userAmount = diffBal.mul(redeemPerc).div(PERCENT_DIVIDER);
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(underTokenAddress), msg.sender, userAmount);
if (diffBal != userAmount) {
// transfer fees to JFeesCollector
feesAmount = diffBal.sub(userAmount);
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(underTokenAddress), feesCollectorAddress, feesAmount);
}
}
// claim and transfer rewards to msg.sender. Be sure to wait for this function to be completed!
bool rewClaimCompleted = IIncentivesController(incentivesControllerAddress).claimRewardsAllMarkets(msg.sender);
// decrease tokens after claiming rewards
if (rewClaimCompleted && _amount > 0)
decreaseTrancheBTokenFromStake(_trancheNum, _amount);
IJTrancheTokens(bTrancheAddress).burn(_amount);
lastActivity[msg.sender] = block.number;
emit TrancheBTokenRedemption(_trancheNum, msg.sender, 0, userAmount, feesAmount);
}
/**
* @dev redeem every cToken amount and send values to fees collector
* @param _trancheNum tranche number
* @param _cTokenAmount cToken amount to send to compound protocol
*/
function redeemCTokenAmount(uint256 _trancheNum, uint256 _cTokenAmount) external onlyAdmins nonReentrant {
uint256 oldBal;
uint256 diffBal;
address underTokenAddress = trancheAddresses[_trancheNum].buyerCoinAddress;
uint256 cTokenBal = getTokenBalance(trancheAddresses[_trancheNum].cTokenAddress); // needed for emergency
if (underTokenAddress == address(0)) {
oldBal = getEthBalance();
ethGateway.withdrawETH(_cTokenAmount, address(this), true, cTokenBal);
diffBal = getEthBalance().sub(oldBal);
TransferETHHelper.safeTransferETH(feesCollectorAddress, diffBal);
} else {
// calculate taToken amount via cToken price
oldBal = getTokenBalance(underTokenAddress);
require(redeemCErc20Tokens(underTokenAddress, _cTokenAmount, true) == 0, "!cTokenAnswer");
// address cToken = cTokenContracts[trancheAddresses[_trancheNum].buyerCoinAddress];
// uint256 compRetCode = IJCompoundHelper(jCompoundHelperAddress).redeemCErc20TokensHelper(cToken, _cTokenAmount, false);
// require(compRetCode == 0, "!cTokenAnswer");
diffBal = getTokenBalance(underTokenAddress);
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(underTokenAddress), feesCollectorAddress, diffBal);
}
}
/**
* @dev get every token balance in this contract
* @param _tokenContract token contract address
*/
function getTokenBalance(address _tokenContract) public view returns (uint256) {
return IERC20Upgradeable(_tokenContract).balanceOf(address(this));
}
/**
* @dev get eth balance on this contract
*/
function getEthBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev transfer tokens in this contract to fees collector contract
* @param _tokenContract token contract address
* @param _amount token amount to be transferred
*/
function transferTokenToFeesCollector(address _tokenContract, uint256 _amount) external onlyAdmins {
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(_tokenContract), feesCollectorAddress, _amount);
}
/**
* @dev transfer ethers in this contract to fees collector contract
* @param _amount ethers amount to be transferred
*/
function withdrawEthToFeesCollector(uint256 _amount) external onlyAdmins {
TransferETHHelper.safeTransferETH(feesCollectorAddress, _amount);
}
/**
* @dev get total accrued Comp token from all market in comptroller
* @return comp amount accrued
*/
function getTotalCompAccrued() public view onlyAdmins returns (uint256) {
return IComptrollerLensInterface(comptrollerAddress).compAccrued(address(this));
}
/**
* @dev claim total accrued Comp token from all market in comptroller and transfer the amount to a receiver address
* @param _receiver destination address
*/
function claimTotalCompAccruedToReceiver(address _receiver) external onlyAdmins nonReentrant {
uint256 totAccruedAmount = getTotalCompAccrued();
if (totAccruedAmount > 0) {
IComptrollerLensInterface(comptrollerAddress).claimComp(address(this));
uint256 amount = IERC20Upgradeable(compTokenAddress).balanceOf(address(this));
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(compTokenAddress), _receiver, amount);
}
}
}
|
set staking details for tranche B holders, with number, amount and time _trancheNum tranche number _account user's account _stkNum staking detail counter _amount amount of tranche B tokens _time time to be considered the deposit/
|
function setTrBStakingDetails(uint256 _trancheNum, address _account, uint256 _stkNum, uint256 _amount, uint256 _time) external onlyAdmins {
stakeCounterTrB[_account][_trancheNum] = _stkNum;
StakingDetails storage details = stakingDetailsTrancheB[_account][_trancheNum][_stkNum];
details.startTime = _time;
details.amount = _amount;
}
| 15,089,863 |
./full_match/42161/0x556D199e955836248098E1c7A5e9a0Fee14a23E6/sources/_layerzerolabs/solidity-examples/contracts/token/onft/IONFT721Core.sol
|
Interface of the ONFT Core standard/
|
interface IONFT721Core is IERC165 {
event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes indexed _toAddress, uint[] _tokenIds);
event ReceiveFromChain(uint16 indexed _srcChainId, bytes indexed _srcAddress, address indexed _toAddress, uint[] _tokenIds);
event CreditStored(bytes32 _hashedPayload, bytes _payload);
event CreditCleared(bytes32 _hashedPayload);
function sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _tokenId, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
function sendBatchFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint[] calldata _tokenIds, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
function estimateSendFee(uint16 _dstChainId, bytes calldata _toAddress, uint _tokenId, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
function estimateSendBatchFee(uint16 _dstChainId, bytes calldata _toAddress, uint[] calldata _tokenIds, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
}
| 16,299,008 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
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() {
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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// minimum amount of funds to be raised in weis
uint256 public goal;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
function RefundableCrowdsale(uint256 _goal) {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
// We're overriding the fund forwarding from Crowdsale.
// In addition to sending the funds, we want to call
// the RefundVault deposit function
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
// vault finalization task, called when owner calls finalize()
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function goalReached() public constant returns (bool) {
return weiRaised >= goal;
}
}
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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
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);
}
}
contract StampifyToken is MintableToken, PausableToken, BurnableToken {
string public constant name = "Stampify Token";
string public constant symbol = "STAMP";
uint8 public constant decimals = 18;
function StampifyToken() {
pause();
}
}
contract TokenCappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
uint256 public tokenSold;
function TokenCappedCrowdsale(uint256 _cap) {
require(_cap > 0);
cap = _cap;
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiToTokens(weiAmount, now);
require(tokenSold.add(tokens) <= cap);
// update state
weiRaised = weiRaised.add(weiAmount);
tokenSold = tokenSold.add(tokens);
token.mint(beneficiary, tokens);
TokenPurchase(
msg.sender,
beneficiary,
weiAmount,
tokens);
forwardFunds();
}
function weiToTokens(uint256 weiAmount, uint256 time) internal returns (uint256) {
uint256 _rate = getRate(time);
return weiAmount.mul(_rate);
}
// low level get rate function
// override to create custom rate function, like giving bonus for early contributors or whitelist addresses
function getRate(uint256 time) internal returns (uint256) {
return rate;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = tokenSold >= cap;
return super.hasEnded() || capReached;
}
}
contract StampifyTokenSale is TokenCappedCrowdsale, RefundableCrowdsale, Pausable {
using SafeMath for uint256;
// Constants
uint256 constant private BIG_BUYER_THRESHOLD = 40 * 10**18; // 40 ETH
uint256 constant public RESERVE_AMOUNT = 25000000 * 10**18; // 25M STAMPS
// Modifiers
modifier isValidDataString(uint256 weiAmount, bytes data) {
if (weiAmount > BIG_BUYER_THRESHOLD) {
require(bytesToBytes32(data) == dataWhitelist[1]);
} else {
require(bytesToBytes32(data) == dataWhitelist[0]);
}
_;
}
// Data types
struct TeamMember {
address wallet; // Address of team member's wallet
address vault; // Address of token timelock vault
uint64 shareDiv; // Divisor to be used to get member's token share
}
// Private
uint64[4] private salePeriods;
bytes32[2] private dataWhitelist;
uint8 private numTeamMembers;
mapping (uint => address) private memberLookup;
// Public
mapping (address => TeamMember) public teamMembers; // founders & contributors vaults (beneficiary,vault) + Org's multisig
function StampifyTokenSale(
uint256 _startTime,
uint256 _endTime,
uint256 _rate,
uint256 _goal,
uint256 _cap,
address _wallet,
uint64[4] _salePeriods,
bytes32[2] _dataWhitelist
)
TokenCappedCrowdsale(_cap)
FinalizableCrowdsale()
RefundableCrowdsale(_goal)
Crowdsale(_startTime, _endTime, _rate, _wallet)
{
require(_goal.mul(_rate) <= _cap);
for (uint8 i = 0; i < _salePeriods.length; i++) {
require(_salePeriods[i] > 0);
}
salePeriods = _salePeriods;
dataWhitelist = _dataWhitelist;
}
function createTokenContract() internal returns (MintableToken) {
return new StampifyToken();
}
function () whenNotPaused isValidDataString(msg.value, msg.data) payable {
super.buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) whenNotPaused isValidDataString(msg.value, msg.data) public payable {
super.buyTokens(beneficiary);
}
// gamification
function getRate(uint256 time) internal returns (uint256) {
if (time <= salePeriods[0]) {
return 750;
}
if (time <= salePeriods[1]) {
return 600;
}
if (time <= salePeriods[2]) {
return 575;
}
if (time <= salePeriods[3]) {
return 525;
}
return rate;
}
function setTeamVault(address _wallet, address _vault, uint64 _shareDiv) onlyOwner public returns (bool) {
require(now < startTime); // Only before sale starts !
require(_wallet != address(0));
require(_vault != address(0));
require(_shareDiv > 0);
require(numTeamMembers + 1 <= 8);
memberLookup[numTeamMembers] = _wallet;
teamMembers[_wallet] = TeamMember(_wallet, _vault, _shareDiv);
numTeamMembers++;
return true;
}
function getTeamVault(address _wallet) constant public returns (address) {
require(_wallet != address(0));
return teamMembers[_wallet].vault;
}
function finalization() internal {
if (goalReached()) {
bool capReached = tokenSold >= cap;
if (!capReached) {
uint256 tokenUnsold = cap.sub(tokenSold);
// Mint unsold tokens to sale's address & burn them immediately
require(token.mint(this, tokenUnsold));
StampifyToken(token).burn(tokenUnsold);
}
uint256 tokenReserved = RESERVE_AMOUNT;
for (uint8 i = 0; i < numTeamMembers; i++) {
TeamMember memory member = teamMembers[memberLookup[i]];
if (member.vault != address(0)) {
var tokenAmount = tokenSold.div(member.shareDiv);
require(token.mint(member.vault, tokenAmount));
tokenReserved = tokenReserved.sub(tokenAmount);
}
}
// Allocate remaining reserve to multisig wallet
require(token.mint(wallet, tokenReserved));
// Finish token minting & unpause transfers
require(token.finishMinting());
StampifyToken(token).unpause();
}
super.finalization();
}
function bytesToBytes32(bytes memory source) returns (bytes32 result) {
if (source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
}
|
Mint unsold tokens to sale's address & burn them immediately
|
function finalization() internal {
if (goalReached()) {
bool capReached = tokenSold >= cap;
if (!capReached) {
uint256 tokenUnsold = cap.sub(tokenSold);
require(token.mint(this, tokenUnsold));
StampifyToken(token).burn(tokenUnsold);
}
uint256 tokenReserved = RESERVE_AMOUNT;
for (uint8 i = 0; i < numTeamMembers; i++) {
TeamMember memory member = teamMembers[memberLookup[i]];
if (member.vault != address(0)) {
var tokenAmount = tokenSold.div(member.shareDiv);
require(token.mint(member.vault, tokenAmount));
tokenReserved = tokenReserved.sub(tokenAmount);
}
}
StampifyToken(token).unpause();
}
super.finalization();
}
| 12,942,207 |
./full_match/1/0x7109DeEb07aa9Eed1e2613F88b2f3E1e6C05163f/sources/contracts/feeDistributor/OracleFeeDistributor.sol
|
Recover ether in a rare case when either service, or client, or referrer refuse to accept ether. _to receiver address _proof Merkle proof (the leaf's sibling, and each non-leaf hash that could not otherwise be calculated without additional leaf nodes) _amountInGwei total CL rewards earned by all validators in GWei (see _validatorCount)
|
function recoverEther(
address payable _to,
bytes32[] calldata _proof,
uint256 _amountInGwei
) external onlyOwner {
if (_to == address(0)) {
revert FeeDistributor__ZeroAddressEthReceiver();
}
this.withdraw(_proof, _amountInGwei);
bool success = P2pAddressLib._sendValueWithoutGasRestrictions(_to, balance);
if (success) {
emit FeeDistributor__EtherRecovered(_to, balance);
revert FeeDistributor__EtherRecoveryFailed(_to, balance);
}
}
| 3,156,411 |
./partial_match/1/0x59a3fa712bc01F3Af4E791BFF6A408dea2BbF39f/sources/Users/chichke/Documents/Work/Freelance/RealT/bridge-v2-chichke/contracts/interfaces/IComplianceRegistry.sol
|
IComplianceRegistry IComplianceRegistry interface/
|
interface IComplianceRegistry {
event AddressAttached(address indexed trustedIntermediary, uint256 indexed userId, address indexed address_);
event AddressDetached(address indexed trustedIntermediary, uint256 indexed userId, address indexed address_);
function userId(address[] calldata _trustedIntermediaries, address _address)
external view returns (uint256, address);
function validUntil(address _trustedIntermediary, uint256 _userId)
external view returns (uint256);
function attribute(address _trustedIntermediary, uint256 _userId, uint256 _key)
external view returns (uint256);
function attributes(address _trustedIntermediary, uint256 _userId, uint256[] calldata _keys)
external view returns (uint256[] memory);
function isAddressValid(address[] calldata _trustedIntermediaries, address _address) external view returns (bool);
function isValid(address _trustedIntermediary, uint256 _userId) external view returns (bool);
function registerUser(
address _address,
uint256[] calldata _attributeKeys,
uint256[] calldata _attributeValues
) external;
function registerUsers(
address[] calldata _addresses,
uint256[] calldata _attributeKeys,
uint256[] calldata _attributeValues
) external;
function attachAddress(uint256 _userId, address _address) external;
function attachAddresses(uint256[] calldata _userIds, address[] calldata _addresses) external;
function detachAddress(address _address) external;
function detachAddresses(address[] calldata _addresses) external;
function updateUserAttributes(
uint256 _userId,
uint256[] calldata _attributeKeys,
uint256[] calldata _attributeValues
) external;
function updateUsersAttributes(
uint256[] calldata _userIds,
uint256[] calldata _attributeKeys,
uint256[] calldata _attributeValues
) external;
function updateTransfers(
address _realm,
address _from,
address _to,
uint256 _value
) external;
function monthlyTransfers(
address _realm,
address[] calldata _trustedIntermediaries,
address _address
) external view returns (uint256);
function yearlyTransfers(
address _realm,
address[] calldata _trustedIntermediaries,
address _address
) external view returns (uint256);
function monthlyInTransfers(
address _realm,
address[] calldata _trustedIntermediaries,
address _address
) external view returns (uint256);
function yearlyInTransfers(
address _realm,
address[] calldata _trustedIntermediaries,
address _address
) external view returns (uint256);
function monthlyOutTransfers(
address _realm,
address[] calldata _trustedIntermediaries,
address _address
) external view returns (uint256);
function yearlyOutTransfers(
address _realm,
address[] calldata _trustedIntermediaries,
address _address
) external view returns (uint256);
function addOnHoldTransfer(
address trustedIntermediary,
address token,
address from,
address to,
uint256 amount
) external;
function getOnHoldTransfers(address trustedIntermediary)
external view returns (
uint256 length,
uint256[] memory id,
address[] memory token,
address[] memory from,
address[] memory to,
uint256[] memory amount
);
function processOnHoldTransfers(uint256[] calldata transfers, uint8[] calldata transferDecisions, bool skipMinBoundaryUpdate) external;
function updateOnHoldMinBoundary(uint256 maxIterations) external;
event TransferOnHold(
address indexed trustedIntermediary,
address indexed token,
address indexed from,
address to,
uint256 amount
);
event TransferApproved(
address indexed trustedIntermediary,
address indexed token,
address indexed from,
address to,
uint256 amount
);
event TransferRejected(
address indexed trustedIntermediary,
address indexed token,
address indexed from,
address to,
uint256 amount
);
event TransferCancelled(
address indexed trustedIntermediary,
address indexed token,
address indexed from,
address to,
uint256 amount
);
Copyright (c) 2019 Mt Pelerin Group Ltd
}
| 2,717,936 |
pragma solidity >=0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "../interfaces/IERC20Token.sol";
contract PoolUpgradable is ERC20Upgradeable{
using SafeERC20Upgradeable for IERC20Token;
IERC20Token public basicToken;
uint256 public totalCap;
mapping (address => uint256) public deposits;
mapping (address => uint256) public withdrawals;
event Deposit(address indexed writer, uint256 amount);
event Withdraw(address indexed writer, uint256 amount);
function __Pool_init(address _basicToken, string memory _description) internal initializer {
__ERC20_init(_description,"_UDP");
__Pool_init_unchained(_basicToken);
}
function __Pool_init_unchained(address _basicToken) internal initializer {
basicToken = IERC20Token(_basicToken);
}
/**
* deposit ERC20 tokens function, assigns Liquidity tokens to provided address.
* @param _amount - amount to deposit
* @param _to - address to assign liquidity tokens to
*/
function depositTo(
uint256 _amount,
address _to
) external virtual {
basicToken.safeTransferFrom(msg.sender, address(this), _amount);
_deposit(_amount, _to);
}
/**
* deposit ERC20 tokens function, assigns Liquidity tokens to msg.sender address.
* @param _amount - amount to deposit
*/
function deposit (
uint256 _amount
) external virtual{
basicToken.safeTransferFrom(msg.sender, address(this), _amount);
_deposit(_amount,msg.sender);
}
/**
* converts spefied amount of Liquidity tokens to Basic Token and returns to user (withdraw). The balance of the User (msg.sender) is decreased by specified amount of
* Liquidity tokens. Resulted amount of tokens are transferred to msg.sender
* @param _amount - amount of liquidity tokens to exchange to Basic token.
*/
function withdraw(uint256 _amount) external virtual{
_withdraw(_amount, msg.sender);
}
/**
* converts spefied amount of Liquidity tokens to Basic Token and returns to user (withdraw). The balance of the User (msg.sender) is decreased by specified amount of Liquidity tokens.
* Resulted amount of tokens are transferred to specified address
* @param _amount - amount of liquidity tokens to exchange to Basic token.
* @param _to - address to send resulted amount of tokens to
*/
function withdrawTo(
uint256 _amount,
address _to
) external virtual {
_withdraw(_amount,_to);
}
function _deposit(uint256 amount, address to) internal virtual {
_beforeDeposit(amount, msg.sender, to);
uint256 mintAmount = totalCap != 0 ? amount.mul(totalSupply()).div(totalCap) : amount.mul(10**uint256(decimals())).div(10**uint256(basicToken.decimals()));
_mint(to, mintAmount);
totalCap = totalCap.add(amount);
// deposits[to] = deposits[to].add(amount);
emit Deposit(to, amount);
_afterDeposit(amount, mintAmount, msg.sender, to);
}
function _withdraw(uint256 amountLiquidity, address to) internal virtual {
_beforeWithdraw(amountLiquidity, msg.sender, to);
uint256 revenue = totalSupply() != 0 ? amountLiquidity.mul(totalCap).div(totalSupply()) : amountLiquidity;
require(revenue <= basicToken.balanceOf(address(this)), "Not enough Basic Token tokens on the balance to withdraw");
totalCap = totalCap.sub(revenue);
_burn(msg.sender, amountLiquidity);
basicToken.safeTransfer(to, revenue);
// withdrawals[msg.sender] = withdrawals[msg.sender].add(revenue);
emit Withdraw(msg.sender, revenue);
_afterWithdraw(revenue, msg.sender, to);
}
function _beforeDeposit(uint256 amountTokenSent, address sender, address holder) internal virtual {}
function _afterDeposit(uint256 amountTokenSent, uint256 amountLiquidityGot, address sender, address holder) internal virtual {}
function _beforeWithdraw(uint256 amountLiquidity, address holder, address receiver) internal virtual {}
function _afterWithdraw(uint256 amountTokenReceived, address holder, address receiver) internal virtual {}
uint256[10] private __gap;
}
|
withdrawals[msg.sender] = withdrawals[msg.sender].add(revenue);
|
function _withdraw(uint256 amountLiquidity, address to) internal virtual {
_beforeWithdraw(amountLiquidity, msg.sender, to);
uint256 revenue = totalSupply() != 0 ? amountLiquidity.mul(totalCap).div(totalSupply()) : amountLiquidity;
require(revenue <= basicToken.balanceOf(address(this)), "Not enough Basic Token tokens on the balance to withdraw");
totalCap = totalCap.sub(revenue);
_burn(msg.sender, amountLiquidity);
basicToken.safeTransfer(to, revenue);
emit Withdraw(msg.sender, revenue);
_afterWithdraw(revenue, msg.sender, to);
}
uint256[10] private __gap;
| 5,366,853 |
./full_match/43113/0x987dcB6fA8Dfb4aC8a6b9a93bEa121c50684b377/sources/MasterChefRef.sol
|
Update the swap router. Can only be called by the current operator./
|
function updateswapRouter() public onlyOperator {
swapRouter = IPangolinRouter(0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106);
swapPair = IPangolinFactory(swapRouter.factory()).getPair(address(this), swapRouter.WAVAX());
require(swapPair != address(0), "updateswapRouter: Invalid pair address.");
emit swapRouterUpdated(msg.sender, address(swapRouter), swapPair);
}
| 7,116,712 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
import "hardhat/console.sol";
contract TheCryptoPurgePortal {
uint256 totalLikes;
/**
* Emit new messages to the portal.
*/
event NewMessage(address indexed from, uint256 timestamp, string message);
/*
* A struct is basically a custom datatype where we can customize what we want to hold inside it.
*/
struct Message {
address user; // The address of the user who waved.
string message; // The message the user sent.
uint256 timestamp; // The timestamp when the user sent the message.
}
/*
* Store an array of messages.
*/
Message[] messages;
/*
* We will be using this below to help generate a "random" number
* will essentially change every time a user call feelingLucky function.
*/
uint256 private seed = 0;
/*
* Cooldowns to prevent spammers
* In this case, We'll be storing the address with the last time a user tried his luck.
*/
mapping(address => uint256) public lastFeelingLuckyAt;
/**
* Emit the prize amount to the lucky user.
*/
event WinPrize(address indexed owner, uint256 prizeAmount);
/*
* Generate a new seed.
* This will be used to generate a random number in a range between 0 - 100.
* block.difficulty - tells miners how hard the block will be to mine based on the transactions in the block.
* block.timestamp - the Unix timestamp that the block is being processed.
*/
function generateSeed() internal {
seed = (block.difficulty + block.timestamp + seed) % 100;
}
constructor() payable {
/*
* Set the initial seed
*/
generateSeed();
console.log("The Crypto Purge Portal :)");
}
function like() public {
totalLikes += 1;
// msg.sender is the address of the account that called the function
console.log("%s has given a like!", msg.sender);
}
function getTotalLikes() public view returns (uint256) {
console.log("We have %d total likes!", totalLikes);
return totalLikes;
}
function sendMessage(string memory message) public {
// msg.sender is the address of the account that called the function
// Store the message in the messages array.
messages.push(Message(msg.sender, message, block.timestamp));
// Emit an event with the message.
emit NewMessage(msg.sender, block.timestamp, message);
}
function getAllMessages() public view returns (Message[] memory) {
return messages;
}
/**
* This function will be called by the user to try his luck.
* The value of the transaction is 0 because this is an internal transaction, the user never paid anything.
*
* All the #'s our contract can access are public and never truly "random" without using Oracles.
* NOTE: DO NOT USE THIS IN PRODUCTION AS IT CAN BE CALLED BY ANY ADDRESS.
* THIS IS PURELY FOR FUN ONLY.
*/
function feelingLucky() public {
/*
* We need to make sure the current timestamp is at least 1-minutes bigger than the last timestamp we stored
*/
require(
lastFeelingLuckyAt[msg.sender] + 1 minutes < block.timestamp,
"Wait 1 minutes before trying again."
);
/*
* Update the current timestamp we have for the user
*/
lastFeelingLuckyAt[msg.sender] = block.timestamp;
/*
* Generate a new seed for the next user
*/
generateSeed();
console.log("The new seed is %s", seed);
/*
* Give a 50% chance that the user wins the prize.
*/
if (seed <= 50) {
/*
* Send the prize.
*/
uint256 prizeAmount = 0.0001 ether;
require(
prizeAmount <= address(this).balance,
"Trying to withdraw more money than the contract has."
);
(bool success, ) = (msg.sender).call{value: prizeAmount}("");
require(success, "Failed to withdraw money from contract.");
emit WinPrize(msg.sender, prizeAmount);
console.log("%s won %d ether!", msg.sender, prizeAmount);
} else {
console.log("Good luck next time! :)");
}
}
}
|
msg.sender is the address of the account that called the function
|
function like() public {
totalLikes += 1;
console.log("%s has given a like!", msg.sender);
}
| 13,070,843 |
./partial_match/1/0x842738637f84b4Dac335b832d9890cf8e11DA214/sources/StakingDFL.sol
|
Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified it is >= amount, this should not revert in normal conditions. Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value./
|
function doTransferOut(address underlying, address to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
assembly {
switch returndatasize()
}
returndatacopy(0, 0, 32)
}
| 2,804,318 |
./partial_match/82/0x267E10BB464d3937613F60655163D11392829E03/sources/Users/huanglu/workspace/ETHEREUM/venus/chee-protocol/contracts/Governance/CHEE.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "CHEE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 16,900,634 |
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
pragma experimental "ABIEncoderV2";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { RebalancingLibrary } from "../../../core/lib/RebalancingLibrary.sol";
/**
* @title ConstantAuctionPriceCurve
* @author Set Protocol
*
* Contract used in rebalancing auction testing to return consistent price
*
*/
contract ConstantAuctionPriceCurve {
using SafeMath for uint256;
uint256 constant public MIN_PIVOT_PRICE_DIVISOR = 2;
uint256 constant public MAX_PIVOT_PRICE_NUMERATOR = 5;
uint256 public priceNumerator;
uint256 public priceDivisor;
/*
* Declare price you want this library to return when queried
*
* @param _priceNumerator The priceNumerator you want this library to always return
* @param _priceDivisor The priceDivisor you want this library to always return
*/
constructor(
uint256 _priceNumerator,
uint256 _priceDivisor
)
public
{
// Set price to be returned by library
priceNumerator = _priceNumerator;
priceDivisor = _priceDivisor;
}
/*
* Validate any auction parameters that have library-specific restrictions
*
* @param _auctionPriceParameters Struct containing relevant auction price parameters
*/
function validateAuctionPriceParameters(
RebalancingLibrary.AuctionPriceParameters memory _auctionPriceParameters
)
public
view
{
// Require pivot price to be greater than 0.5 * price denominator
// Equivalent to oldSet/newSet = 0.5
require(
_auctionPriceParameters.auctionPivotPrice > priceDivisor.div(MIN_PIVOT_PRICE_DIVISOR),
"LinearAuctionPriceCurve.validateAuctionPriceParameters: Pivot price too low"
);
// Require pivot price to be less than 5 * price denominator
// Equivalent to oldSet/newSet = 5
require(
_auctionPriceParameters.auctionPivotPrice < priceDivisor.mul(MAX_PIVOT_PRICE_NUMERATOR),
"LinearAuctionPriceCurve.validateAuctionPriceParameters: Pivot price too high"
);
}
/*
* Calculate the current priceRatio for an auction given defined price and time parameters
*
* -- Unused _auctionPriceParameters param containing relevant auction price parameters --
* @return uint256 The auction price numerator
* @return uint256 The auction price denominator
*/
function getCurrentPrice(
RebalancingLibrary.AuctionPriceParameters memory
)
public
view
returns (uint256, uint256)
{
return (priceNumerator, priceDivisor);
}
}
|
Validate any auction parameters that have library-specific restrictions _auctionPriceParameters Struct containing relevant auction price parameters/ Require pivot price to be greater than 0.5 price denominator Equivalent to oldSet/newSet = 0.5 Require pivot price to be less than 5 price denominator Equivalent to oldSet/newSet = 5
|
function validateAuctionPriceParameters(
RebalancingLibrary.AuctionPriceParameters memory _auctionPriceParameters
)
public
view
{
require(
_auctionPriceParameters.auctionPivotPrice > priceDivisor.div(MIN_PIVOT_PRICE_DIVISOR),
"LinearAuctionPriceCurve.validateAuctionPriceParameters: Pivot price too low"
);
require(
_auctionPriceParameters.auctionPivotPrice < priceDivisor.mul(MAX_PIVOT_PRICE_NUMERATOR),
"LinearAuctionPriceCurve.validateAuctionPriceParameters: Pivot price too high"
);
}
| 6,349,313 |
./full_match/42161/0xB35832761433BaD6C66cC56af8AE9362c07BE21b/sources/contracts/Collateral.sol
|
If hook not set, fees remain within the contract as extra reserves (withdrawable by manager). Converts amount after fee from base token units to collateral token units./
|
function deposit(address recipient, uint256 baseTokenAmount)
external
override
nonReentrant
returns (uint256 collateralMintAmount)
{
uint256 fee = (baseTokenAmount * _depositFee) / PERCENT_DENOMINATOR;
if (_depositFee > 0) {
require(fee > 0, "fee = 0");
require(baseTokenAmount > 0, "base token amount = 0");
}
_baseToken.transferFrom(msg.sender, address(this), baseTokenAmount);
uint256 baseTokenAmountAfterFee = baseTokenAmount - fee;
if (address(_depositHook) != address(0)) {
_baseToken.approve(address(_depositHook), fee);
_depositHook.hook(
msg.sender,
recipient,
baseTokenAmount,
baseTokenAmountAfterFee
);
_baseToken.approve(address(_depositHook), 0);
}
collateralMintAmount =
(baseTokenAmountAfterFee * 1e18) /
_baseTokenDenominator;
_mint(recipient, collateralMintAmount);
emit Deposit(recipient, baseTokenAmountAfterFee, fee);
}
| 16,298,370 |
pragma solidity >=0.8.4;
import "./ENS.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../root/Controllable.sol";
// function _claimWithResolver
// 1. reverse node가 records_list 어딘가에 있다.
// 1)해당 record의 resolver값이 있는 경우
// currentResolver가 해당 resolver를 받아옴.
// 지금 인자로 받아온 resolver가 현재 record에 있는 resolveㄱ와 다르다면 newResolver (인자로 받은 resolver)로 record 업데이트
// 2)해당 record의 resolver값이 0x0인 경우 (resolver가 없는 경우)
// update nono
// 2. reverse node가 record어딘가에 없는 경우 (resolver값이 0x0인 경우)
// update no
// function claim(address owner)의 경우
// _claimWithResolver(msg.sender, owner, address(0x0));를 실행하므로
// resolver값을 일부러 0x0을 줘서 reverse subdomain의 owner만 바뀌게 만듬.
// 메세지를 보낸 사람의 이더 주소의 addr.reverse 노드의 ownership을 건드림
// function claimForAddr(address addr, address owner)
// claim과 거의 같음.
// 차이점은 메세지를 보낸 사람의 이더 주소의 reverse 노드가 아니라
// 특정 addr의 reverse node를 건드림. --> authorized modifier가 붙음
// function claimWithResolver(address owner, address resolver)
// 메세지 보낸 사람의 이더 주소의 reverse 노드를 건드림.
// owner뿐만 아니라 resolver주소까지 받아서 record를 새로 갱신함.
// function claimWithResolverForAddr (address addr, address owner, address resolver)
// 특정 addr의 reverse node를 건드려서 owner와 resolver주소를 갱신.
// --> authorized modifier가 붙음
// function setName(string memory name)
// 이 메세지를 보낸 사람의 이더 주소의 reverse 노드를 찾아서
// owner를 이 컨트랙 주소로, resolver를 defaultResolver로 세팅한 후
// defaultResolver에서 이 노드에 대해 name을 매칭시켜줌
// function setNameForAddr(address addr, address owner, string memory name)
// 특정 addr의 reverse node를 찾아서 owner를 이 컨트랙 주소로, resolver를 defaultResolver로 세팅한 후
// setName 함수와 같이 defaultResolver에서 이 노드에 대해 name 매칭
// 그리고 나서 ensRegistry의 setSubnodeOwner를 받아, 해당 node의 주인을 인자로 받았던 owner로 바꿈 (바로 전에 owner를 이 컨트랙(ReverseRegistrar)으로 바꿔놨기 때문에 가능)
abstract contract NameResolver {
function setName(bytes32 node, string memory name) public virtual;
}
bytes32 constant lookup = 0x3031323334353637383961626364656600000000000000000000000000000000;
bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
// namehash('addr.reverse')
contract ReverseRegistrar is Ownable, Controllable {
ENS public ens;
NameResolver public defaultResolver;
event ReverseClaimed(address indexed addr, bytes32 indexed node);
/**
* @dev Constructor
* @param ensAddr The address of the ENS registry.
* @param resolverAddr The address of the default reverse resolver.
*/
constructor(ENS ensAddr, NameResolver resolverAddr) {
ens = ensAddr;
defaultResolver = resolverAddr;
// Assign ownership of the reverse record to our deployer
ReverseRegistrar oldRegistrar = ReverseRegistrar(
ens.owner(ADDR_REVERSE_NODE)
);
if (address(oldRegistrar) != address(0x0)) {
oldRegistrar.claim(msg.sender);
}
}
modifier authorised(address addr) {
require(
addr == msg.sender ||
controllers[msg.sender] ||
ens.isApprovedForAll(addr, msg.sender) ||
ownsContract(addr),
"Caller is not a controller or authorised by address or the address itself"
);
_;
}
/**
* @dev Transfers ownership of the reverse ENS record associated with the
* calling account.
* @param owner The address to set as the owner of the reverse record in ENS.
* @return The ENS node hash of the reverse record.
*/
function claim(address owner) public returns (bytes32) {
return _claimWithResolver(msg.sender, owner, address(0x0));
}
/**
* @dev Transfers ownership of the reverse ENS record associated with the
* calling account.
* @param addr The reverse record to set
* @param owner The address to set as the owner of the reverse record in ENS.
* @return The ENS node hash of the reverse record.
*/
function claimForAddr(address addr, address owner)
public
authorised(addr)
returns (bytes32)
{
return _claimWithResolver(addr, owner, address(0x0));
}
/**
* @dev Transfers ownership of the reverse ENS record associated with the
* calling account.
* @param owner The address to set as the owner of the reverse record in ENS.
* @param resolver The address of the resolver to set; 0 to leave unchanged.
* @return The ENS node hash of the reverse record.
*/
function claimWithResolver(address owner, address resolver)
public
returns (bytes32)
{
return _claimWithResolver(msg.sender, owner, resolver);
}
/**
* @dev Transfers ownership of the reverse ENS record specified with the
* address provided
* @param addr The reverse record to set
* @param owner The address to set as the owner of the reverse record in ENS.
* @param resolver The address of the resolver to set; 0 to leave unchanged.
* @return The ENS node hash of the reverse record.
*/
function claimWithResolverForAddr(
address addr,
address owner,
address resolver
) public authorised(addr) returns (bytes32) {
return _claimWithResolver(addr, owner, resolver);
}
/**
* @dev Sets the `name()` record for the reverse ENS record associated with
* the calling account. First updates the resolver to the default reverse
* resolver if necessary.
* @param name The name to set for this address.
* @return The ENS node hash of the reverse record.
*/
function setName(string memory name) public returns (bytes32) {
bytes32 node = _claimWithResolver(
msg.sender,
address(this),
address(defaultResolver)
);
defaultResolver.setName(node, name);
return node;
}
/**
* @dev Sets the `name()` record for the reverse ENS record associated with
* the account provided. First updates the resolver to the default reverse
* resolver if necessary.
* Only callable by controllers and authorised users
* @param addr The reverse record to set
* @param owner The owner of the reverse node
* @param name The name to set for this address.
* @return The ENS node hash of the reverse record.
*/
function setNameForAddr(
address addr,
address owner,
string memory name
) public authorised(addr) returns (bytes32) {
bytes32 node = _claimWithResolver(
addr,
address(this),
address(defaultResolver)
);
defaultResolver.setName(node, name);
ens.setSubnodeOwner(ADDR_REVERSE_NODE, sha3HexAddress(addr), owner);
return node;
}
/**
* @dev Returns the node hash for a given account's reverse records.
* @param addr The address to hash
* @return The ENS node hash.
*/
function node(address addr) public pure returns (bytes32) {
return
keccak256(
abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr))
);
}
/**
* @dev An optimised function to compute the sha3 of the lower-case
* hexadecimal representation of an Ethereum address.
* @param addr The address to hash
* @return ret The SHA3 hash of the lower-case hexadecimal encoding of the
* input address.
*/
function sha3HexAddress(address addr) private pure returns (bytes32 ret) {
assembly {
for {
let i := 40
} gt(i, 0) {
} {
i := sub(i, 1)
mstore8(i, byte(and(addr, 0xf), lookup))
addr := div(addr, 0x10)
i := sub(i, 1)
mstore8(i, byte(and(addr, 0xf), lookup))
addr := div(addr, 0x10)
}
ret := keccak256(0, 40)
}
}
/* Internal functions */
// addr의 reverse node를 찾아 owner와 resolver를 set하는 함수
// reverse node가 records_list어딘가의 resolver에 이미 있는지 없는지 확인하고 없으면 새로운 resolver를 갱신해서
// record에 병합하여 setSubnodeRecord실행.
function _claimWithResolver(
address addr,
address owner,
address resolver
) internal returns (bytes32) {
bytes32 label = sha3HexAddress(addr); //addr을 sha3값으로 변환
bytes32 node = keccak256(abi.encodePacked(ADDR_REVERSE_NODE, label)); // {addr}{addr.reverse} 의 namehash가 input으로 들어가는 상황
address currentResolver = ens.resolver(node);
bool shouldUpdateResolver = (resolver != address(0x0) &&
resolver != currentResolver);
address newResolver = shouldUpdateResolver ? resolver : currentResolver;
ens.setSubnodeRecord(ADDR_REVERSE_NODE, label, owner, newResolver, 0);
emit ReverseClaimed(addr, node);
return node;
}
function ownsContract(address addr) internal view returns (bool) {
try Ownable(addr).owner() returns (address owner) {
return owner == msg.sender;
} catch {
return false;
}
}
}
|
Transfers ownership of the reverse ENS record associated with the calling account. owner The address to set as the owner of the reverse record in ENS. resolver The address of the resolver to set; 0 to leave unchanged. return The ENS node hash of the reverse record./
|
function claimWithResolver(address owner, address resolver)
public
returns (bytes32)
{
return _claimWithResolver(msg.sender, owner, resolver);
}
| 1,031,081 |
pragma solidity ^0.5.7;
contract SafeTransfer {
function _SAFETRANSFER911(ERC20Token _token, address _to, uint256 _value) internal returns (bool result) { //inject NONSTANDARD NAMING
_token.TRANSFER494(_to, _value);
assembly {
switch returndatasize()
case 0 {
result := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
result := mload(0)
}
default {
revert(0, 0)
}
}
require(result, "Unsuccessful token transfer");
}
function _SAFETRANSFERFROM345( //inject NONSTANDARD NAMING
ERC20Token _token,
address _from,
address _to,
uint256 _value
) internal returns (bool result)
{
_token.TRANSFERFROM513(_from, _to, _value);
assembly {
switch returndatasize()
case 0 {
result := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
result := mload(0)
}
default {
revert(0, 0)
}
}
require(result, "Unsuccessful token transfer");
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
interface ERC20Token {
function TRANSFER494(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function APPROVE813(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM513(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function BALANCEOF691(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function ALLOWANCE536(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING
function TOTALSUPPLY245() external view returns (uint256 supply); //inject NONSTANDARD NAMING
event TRANSFER151(address indexed _from, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING
event APPROVAL845(address indexed _owner, address indexed _spender, uint256 _value); //inject NONSTANDARD NAMING
}
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED396(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED396(address(0), _owner);
}
function OWNER296() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER677() { //inject NONSTANDARD NAMING
require(ISOWNER71(), "Only the contract's owner can invoke this function");
_;
}
function _SETOWNER235(address _newOwner) internal { //inject NONSTANDARD NAMING
_owner = _newOwner;
}
function ISOWNER71() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP275() external ONLYOWNER677 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED396(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP770(address _newOwner) external ONLYOWNER677 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP486(_newOwner);
}
function _TRANSFEROWNERSHIP486(address _newOwner) internal { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "New owner cannot be address(0)");
emit OWNERSHIPTRANSFERRED396(_owner, _newOwner);
_owner = _newOwner;
}
}
contract ReentrancyGuard {
bool public locked = false;
modifier REENTRANCYGUARD399() { //inject NONSTANDARD NAMING
require(!locked, "Reentrant call detected!");
locked = true;
_;
locked = false;
}
}
contract Proxiable {
// Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"
event UPGRADED572(address indexed implementation); //inject NONSTANDARD NAMING
function UPDATECODEADDRESS579(address newAddress) internal { //inject NONSTANDARD NAMING
require(
bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).PROXIABLEUUID20(),
"Not compatible"
);
assembly { // solium-disable-line
sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress)
}
emit UPGRADED572(newAddress);
}
function PROXIABLEUUID20() public pure returns (bytes32) { //inject NONSTANDARD NAMING
return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7;
}
bool internal _initialized;
function ISINITIALIZED692() public view returns(bool) { //inject NONSTANDARD NAMING
return _initialized;
}
}
contract SecuredFunctions is Ownable {
mapping(address => bool) public allowedContracts;
modifier ONLYALLOWEDCONTRACTS234 { //inject NONSTANDARD NAMING
require(allowedContracts[msg.sender] || msg.sender == address(this), "Only allowed contracts can invoke this function");
_;
}
function SETALLOWEDCONTRACT466 ( //inject NONSTANDARD NAMING
address _contract,
bool _allowed
) public ONLYOWNER677 {
allowedContracts[_contract] = _allowed;
}
}
contract MessageSigned {
constructor() internal {}
function _RECOVERADDRESS15(bytes32 _signHash, bytes memory _messageSignature) //inject NONSTANDARD NAMING
internal
pure
returns(address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v,r,s) = SIGNATURESPLIT549(_messageSignature);
return ecrecover(_signHash, v, r, s);
}
function _GETSIGNHASH525(bytes32 _hash) internal pure returns (bytes32 signHash) { //inject NONSTANDARD NAMING
signHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash));
}
function SIGNATURESPLIT549(bytes memory _signature) //inject NONSTANDARD NAMING
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(_signature.length == 65, "Bad signature length");
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
// Here we are loading the last 32 bytes, including 31 bytes
// of 's'. There is no 'mload8' to do this.
//
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "Bad signature version");
}
}
contract ApproveAndCallFallBack {
function RECEIVEAPPROVAL139(address from, uint256 _amount, address _token, bytes memory _data) public; //inject NONSTANDARD NAMING
}
contract License is Ownable, ApproveAndCallFallBack, SafeTransfer, Proxiable {
uint256 public price;
ERC20Token token;
address burnAddress;
struct LicenseDetails {
uint price;
uint creationTime;
}
address[] public licenseOwners;
mapping(address => uint) public idxLicenseOwners;
mapping(address => LicenseDetails) public licenseDetails;
event BOUGHT91(address buyer, uint256 price); //inject NONSTANDARD NAMING
event PRICECHANGED925(uint256 _price); //inject NONSTANDARD NAMING
event BURNADDRESSCHANGED16(address sender, address prevBurnAddress, address newBurnAddress); //inject NONSTANDARD NAMING
function SETBURNADDRESS147(address payable _burnAddress) external ONLYOWNER677 { //inject NONSTANDARD NAMING
emit BURNADDRESSCHANGED16(msg.sender, burnAddress, _burnAddress);
burnAddress = _burnAddress;
}
constructor(address _tokenAddress, uint256 _price, address _burnAddress) public {
INIT444(_tokenAddress, _price, _burnAddress);
}
function INIT444( //inject NONSTANDARD NAMING
address _tokenAddress,
uint256 _price,
address _burnAddress
) public {
assert(_initialized == false);
_initialized = true;
price = _price;
token = ERC20Token(_tokenAddress);
burnAddress = _burnAddress;
_SETOWNER235(msg.sender);
}
function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING
UPDATECODEADDRESS579(newCode);
}
function ISLICENSEOWNER342(address _address) public view returns (bool) { //inject NONSTANDARD NAMING
return licenseDetails[_address].price != 0 && licenseDetails[_address].creationTime != 0;
}
function BUY699() external returns(uint) { //inject NONSTANDARD NAMING
uint id = _BUYFROM536(msg.sender);
return id;
}
function _BUYFROM536(address _licenseOwner) internal returns(uint) { //inject NONSTANDARD NAMING
require(licenseDetails[_licenseOwner].creationTime == 0, "License already bought");
licenseDetails[_licenseOwner] = LicenseDetails({
price: price,
creationTime: block.timestamp
});
uint idx = licenseOwners.push(_licenseOwner);
idxLicenseOwners[_licenseOwner] = idx;
emit BOUGHT91(_licenseOwner, price);
require(_SAFETRANSFERFROM345(token, _licenseOwner, burnAddress, price), "Unsuccessful token transfer");
return idx;
}
function SETPRICE121(uint256 _price) external ONLYOWNER677 { //inject NONSTANDARD NAMING
price = _price;
emit PRICECHANGED925(_price);
}
function GETNUMLICENSEOWNERS215() external view returns (uint256) { //inject NONSTANDARD NAMING
return licenseOwners.length;
}
function RECEIVEAPPROVAL139(address _from, uint256 _amount, address _token, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_amount == price, "Wrong value");
require(_token == address(token), "Wrong token");
require(_token == address(msg.sender), "Wrong call");
require(_data.length == 4, "Wrong data length");
require(_ABIDECODEBUY25(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()"))
_BUYFROM536(_from);
}
function _ABIDECODEBUY25(bytes memory _data) internal pure returns(bytes4 sig) { //inject NONSTANDARD NAMING
assembly {
sig := mload(add(_data, add(0x20, 0)))
}
}
}
contract IEscrow {
enum EscrowStatus {CREATED, FUNDED, PAID, RELEASED, CANCELED}
struct EscrowTransaction {
uint256 offerId;
address token;
uint256 tokenAmount;
uint256 expirationTime;
uint256 sellerRating;
uint256 buyerRating;
uint256 fiatAmount;
address payable buyer;
address payable seller;
address payable arbitrator;
address payable destination;
EscrowStatus status;
}
function CREATEESCROW_RELAYED829( //inject NONSTANDARD NAMING
address payable _sender,
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
address payable _destination,
string calldata _contactData,
string calldata _location,
string calldata _username
) external returns(uint escrowId);
function PAY204(uint _escrowId) external; //inject NONSTANDARD NAMING
function PAY_RELAYED312(address _sender, uint _escrowId) external; //inject NONSTANDARD NAMING
function CANCEL601(uint _escrowId) external; //inject NONSTANDARD NAMING
function CANCEL_RELAYED801(address _sender, uint _escrowId) external; //inject NONSTANDARD NAMING
function OPENCASE508(uint _escrowId, uint8 _motive) external; //inject NONSTANDARD NAMING
function OPENCASE_RELAYED502(address _sender, uint256 _escrowId, uint8 _motive) external; //inject NONSTANDARD NAMING
function RATETRANSACTION74(uint _escrowId, uint _rate) external; //inject NONSTANDARD NAMING
function RATETRANSACTION_RELAYED289(address _sender, uint _escrowId, uint _rate) external; //inject NONSTANDARD NAMING
function GETBASICTRADEDATA166(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount); //inject NONSTANDARD NAMING
}
contract Pausable is Ownable {
event PAUSED628(); //inject NONSTANDARD NAMING
event UNPAUSED643(); //inject NONSTANDARD NAMING
bool public paused;
constructor () internal {
paused = false;
}
modifier WHENNOTPAUSED504() { //inject NONSTANDARD NAMING
require(!paused, "Contract must be unpaused");
_;
}
modifier WHENPAUSED494() { //inject NONSTANDARD NAMING
require(paused, "Contract must be paused");
_;
}
function PAUSE819() external ONLYOWNER677 WHENNOTPAUSED504 { //inject NONSTANDARD NAMING
paused = true;
emit PAUSED628();
}
function UNPAUSE973() external ONLYOWNER677 WHENPAUSED494 { //inject NONSTANDARD NAMING
paused = false;
emit UNPAUSED643();
}
}
contract ArbitrationLicense is License {
enum RequestStatus {NONE,AWAIT,ACCEPTED,REJECTED,CLOSED}
struct Request{
address seller;
address arbitrator;
RequestStatus status;
uint date;
}
struct ArbitratorLicenseDetails {
uint id;
bool acceptAny;// accept any seller
}
mapping(address => ArbitratorLicenseDetails) public arbitratorlicenseDetails;
mapping(address => mapping(address => bool)) public permissions;
mapping(address => mapping(address => bool)) public blacklist;
mapping(bytes32 => Request) public requests;
event ARBITRATORREQUESTED586(bytes32 id, address indexed seller, address indexed arbitrator); //inject NONSTANDARD NAMING
event REQUESTACCEPTED10(bytes32 id, address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING
event REQUESTREJECTED172(bytes32 id, address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING
event REQUESTCANCELED901(bytes32 id, address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING
event BLACKLISTSELLER899(address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING
event UNBLACKLISTSELLER540(address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING
constructor(address _tokenAddress, uint256 _price, address _burnAddress)
License(_tokenAddress, _price, _burnAddress)
public {}
function BUY699() external returns(uint) { //inject NONSTANDARD NAMING
return _BUY66(msg.sender, false);
}
function BUY699(bool _acceptAny) external returns(uint) { //inject NONSTANDARD NAMING
return _BUY66(msg.sender, _acceptAny);
}
function _BUY66(address _sender, bool _acceptAny) internal returns (uint id) { //inject NONSTANDARD NAMING
id = _BUYFROM536(_sender);
arbitratorlicenseDetails[_sender].id = id;
arbitratorlicenseDetails[_sender].acceptAny = _acceptAny;
}
function CHANGEACCEPTANY798(bool _acceptAny) public { //inject NONSTANDARD NAMING
require(ISLICENSEOWNER342(msg.sender), "Message sender should have a valid arbitrator license");
require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny,
"Message sender should pass parameter different from the current one");
arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny;
}
function REQUESTARBITRATOR791(address _arbitrator) public { //inject NONSTANDARD NAMING
require(ISLICENSEOWNER342(_arbitrator), "Arbitrator should have a valid license");
require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases");
bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender));
RequestStatus _status = requests[_id].status;
require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status");
if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){
require(requests[_id].date + 3 days < block.timestamp,
"Must wait 3 days before requesting the arbitrator again");
}
requests[_id] = Request({
seller: msg.sender,
arbitrator: _arbitrator,
status: RequestStatus.AWAIT,
date: block.timestamp
});
emit ARBITRATORREQUESTED586(_id, msg.sender, _arbitrator);
}
function GETID524(address _arbitrator, address _account) external pure returns(bytes32){ //inject NONSTANDARD NAMING
return keccak256(abi.encodePacked(_arbitrator,_account));
}
function ACCEPTREQUEST19(bytes32 _id) public { //inject NONSTANDARD NAMING
require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license");
require(requests[_id].status == RequestStatus.AWAIT, "This request is not pending");
require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator already accepts all cases");
require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator");
requests[_id].status = RequestStatus.ACCEPTED;
address _seller = requests[_id].seller;
permissions[msg.sender][_seller] = true;
emit REQUESTACCEPTED10(_id, msg.sender, requests[_id].seller);
}
function REJECTREQUEST397(bytes32 _id) public { //inject NONSTANDARD NAMING
require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license");
require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED,
"Invalid request status");
require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator accepts all cases");
require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator");
requests[_id].status = RequestStatus.REJECTED;
requests[_id].date = block.timestamp;
address _seller = requests[_id].seller;
permissions[msg.sender][_seller] = false;
emit REQUESTREJECTED172(_id, msg.sender, requests[_id].seller);
}
function CANCELREQUEST262(bytes32 _id) public { //inject NONSTANDARD NAMING
require(requests[_id].seller == msg.sender, "This request id does not belong to the message sender");
require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status");
address arbitrator = requests[_id].arbitrator;
requests[_id].status = RequestStatus.CLOSED;
requests[_id].date = block.timestamp;
address _arbitrator = requests[_id].arbitrator;
permissions[_arbitrator][msg.sender] = false;
emit REQUESTCANCELED901(_id, arbitrator, requests[_id].seller);
}
function BLACKLISTSELLER470(address _seller) public { //inject NONSTANDARD NAMING
require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license");
blacklist[msg.sender][_seller] = true;
emit BLACKLISTSELLER899(msg.sender, _seller);
}
function UNBLACKLISTSELLER351(address _seller) public { //inject NONSTANDARD NAMING
require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license");
blacklist[msg.sender][_seller] = false;
emit UNBLACKLISTSELLER540(msg.sender, _seller);
}
function ISALLOWED574(address _seller, address _arbitrator) public view returns(bool) { //inject NONSTANDARD NAMING
return (arbitratorlicenseDetails[_arbitrator].acceptAny && !blacklist[_arbitrator][_seller]) || permissions[_arbitrator][_seller];
}
function RECEIVEAPPROVAL139(address _from, uint256 _amount, address _token, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_amount == price, "Wrong value");
require(_token == address(token), "Wrong token");
require(_token == address(msg.sender), "Wrong call");
require(_data.length == 4, "Wrong data length");
require(_ABIDECODEBUY25(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()"))
_BUY66(_from, false);
}
}
contract UserStore is MessageSigned, SecuredFunctions, Proxiable {
struct User {
string contactData;
string location;
string username;
}
License public sellingLicenses;
ArbitrationLicense public arbitrationLicenses;
mapping(address => User) public users;
mapping(address => uint) public user_nonce;
constructor(address _sellingLicenses, address _arbitrationLicenses) public
{
INIT444(_sellingLicenses, _arbitrationLicenses);
}
function INIT444( //inject NONSTANDARD NAMING
address _sellingLicenses,
address _arbitrationLicenses
) public {
assert(_initialized == false);
_initialized = true;
sellingLicenses = License(_sellingLicenses);
arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses);
_SETOWNER235(msg.sender);
}
function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING
UPDATECODEADDRESS579(newCode);
}
event LICENSESCHANGED569(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses); //inject NONSTANDARD NAMING
function SETLICENSES678( //inject NONSTANDARD NAMING
address _sellingLicenses,
address _arbitrationLicenses
) public ONLYOWNER677 {
emit LICENSESCHANGED569(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses));
sellingLicenses = License(_sellingLicenses);
arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses);
}
function _DATAHASH273(string memory _username, string memory _contactData, uint _nonce) internal view returns (bytes32) { //inject NONSTANDARD NAMING
return keccak256(abi.encodePacked(address(this), _username, _contactData, _nonce));
}
function GETDATAHASH823(string calldata _username, string calldata _contactData) external view returns (bytes32) { //inject NONSTANDARD NAMING
return _DATAHASH273(_username, _contactData, user_nonce[msg.sender]);
}
function _GETSIGNER107( //inject NONSTANDARD NAMING
string memory _username,
string memory _contactData,
uint _nonce,
bytes memory _signature
) internal view returns(address) {
bytes32 signHash = _GETSIGNHASH525(_DATAHASH273(_username, _contactData, _nonce));
return _RECOVERADDRESS15(signHash, _signature);
}
function GETMESSAGESIGNER993( //inject NONSTANDARD NAMING
string calldata _username,
string calldata _contactData,
uint _nonce,
bytes calldata _signature
) external view returns(address) {
return _GETSIGNER107(_username, _contactData, _nonce, _signature);
}
function _ADDORUPDATEUSER76( //inject NONSTANDARD NAMING
address _user,
string memory _contactData,
string memory _location,
string memory _username
) internal {
User storage u = users[_user];
u.contactData = _contactData;
u.location = _location;
u.username = _username;
}
function ADDORUPDATEUSER850( //inject NONSTANDARD NAMING
bytes calldata _signature,
string calldata _contactData,
string calldata _location,
string calldata _username,
uint _nonce
) external returns(address payable _user) {
_user = address(uint160(_GETSIGNER107(_username, _contactData, _nonce, _signature)));
require(_nonce == user_nonce[_user], "Invalid nonce");
user_nonce[_user]++;
_ADDORUPDATEUSER76(_user, _contactData, _location, _username);
return _user;
}
function ADDORUPDATEUSER850( //inject NONSTANDARD NAMING
string calldata _contactData,
string calldata _location,
string calldata _username
) external {
_ADDORUPDATEUSER76(msg.sender, _contactData, _location, _username);
}
function ADDORUPDATEUSER850( //inject NONSTANDARD NAMING
address _sender,
string calldata _contactData,
string calldata _location,
string calldata _username
) external ONLYALLOWEDCONTRACTS234 {
_ADDORUPDATEUSER76(_sender, _contactData, _location, _username);
}
}
contract Stakable is Ownable, SafeTransfer {
uint public basePrice = 0.01 ether;
address payable public burnAddress;
struct Stake {
uint amount;
address payable owner;
address token;
}
mapping(uint => Stake) public stakes;
mapping(address => uint) public stakeCounter;
event BURNADDRESSCHANGED16(address sender, address prevBurnAddress, address newBurnAddress); //inject NONSTANDARD NAMING
event BASEPRICECHANGED745(address sender, uint prevPrice, uint newPrice); //inject NONSTANDARD NAMING
event STAKED319(uint indexed itemId, address indexed owner, uint amount); //inject NONSTANDARD NAMING
event UNSTAKED65(uint indexed itemId, address indexed owner, uint amount); //inject NONSTANDARD NAMING
event SLASHED89(uint indexed itemId, address indexed owner, address indexed slasher, uint amount); //inject NONSTANDARD NAMING
constructor(address payable _burnAddress) public {
burnAddress = _burnAddress;
}
function SETBURNADDRESS147(address payable _burnAddress) external ONLYOWNER677 { //inject NONSTANDARD NAMING
emit BURNADDRESSCHANGED16(msg.sender, burnAddress, _burnAddress);
burnAddress = _burnAddress;
}
function SETBASEPRICE977(uint _basePrice) external ONLYOWNER677 { //inject NONSTANDARD NAMING
emit BASEPRICECHANGED745(msg.sender, basePrice, _basePrice);
basePrice = _basePrice;
}
function _STAKE330(uint _itemId, address payable _owner, address _tokenAddress) internal { //inject NONSTANDARD NAMING
require(stakes[_itemId].owner == address(0), "Already has/had a stake");
stakeCounter[_owner]++;
uint stakeAmount = basePrice * stakeCounter[_owner] * stakeCounter[_owner]; // y = basePrice * x^2
// Using only ETH as stake for phase 0
_tokenAddress = address(0);
require(msg.value == stakeAmount, "ETH amount is required");
// Uncomment to support tokens
stakes[_itemId].amount = stakeAmount;
stakes[_itemId].owner = _owner;
stakes[_itemId].token = _tokenAddress;
emit STAKED319(_itemId, _owner, stakeAmount);
}
function GETAMOUNTTOSTAKE537(address _owner) public view returns(uint){ //inject NONSTANDARD NAMING
uint stakeCnt = stakeCounter[_owner] + 1;
return basePrice * stakeCnt * stakeCnt; // y = basePrice * x^2
}
function _UNSTAKE786(uint _itemId) internal { //inject NONSTANDARD NAMING
Stake storage s = stakes[_itemId];
if (s.amount == 0) return; // No stake for item
uint amount = s.amount;
s.amount = 0;
assert(stakeCounter[s.owner] > 0);
stakeCounter[s.owner]--;
if (s.token == address(0)) {
(bool success, ) = s.owner.call.value(amount)("");
require(success, "Transfer failed.");
} else {
require(_SAFETRANSFER911(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds");
}
emit UNSTAKED65(_itemId, s.owner, amount);
}
function _SLASH319(uint _itemId) internal { //inject NONSTANDARD NAMING
Stake storage s = stakes[_itemId];
// TODO: what happens if offer was previosly validated and the user removed the stake?
if (s.amount == 0) return;
uint amount = s.amount;
s.amount = 0;
if (s.token == address(0)) {
(bool success, ) = burnAddress.call.value(amount)("");
require(success, "Transfer failed.");
} else {
require(_SAFETRANSFER911(ERC20Token(s.token), burnAddress, amount), "Couldn't transfer funds");
}
emit SLASHED89(_itemId, s.owner, msg.sender, amount);
}
function _REFUNDSTAKE66(uint _itemId) internal { //inject NONSTANDARD NAMING
Stake storage s = stakes[_itemId];
if (s.amount == 0) return;
uint amount = s.amount;
s.amount = 0;
stakeCounter[s.owner]--;
if (amount != 0) {
if (s.token == address(0)) {
(bool success, ) = s.owner.call.value(amount)("");
require(success, "Transfer failed.");
} else {
require(_SAFETRANSFER911(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds");
}
}
}
}
contract OfferStore is Stakable, SecuredFunctions, Proxiable {
struct Offer {
int16 margin;
uint[] paymentMethods;
uint limitL;
uint limitU;
address asset;
string currency;
address payable owner;
address payable arbitrator;
bool deleted;
}
License public sellingLicenses;
ArbitrationLicense public arbitrationLicenses;
UserStore public userStore;
Offer[] public offers;
mapping(address => uint256[]) public addressToOffers;
mapping(address => mapping (uint256 => bool)) public offerWhitelist;
event OFFERADDED246( //inject NONSTANDARD NAMING
address owner,
uint256 offerId,
address asset,
string location,
string currency,
string username,
uint[] paymentMethods,
uint limitL,
uint limitU,
int16 margin
);
event OFFERREMOVED496(address owner, uint256 offerId); //inject NONSTANDARD NAMING
constructor(address _userStore, address _sellingLicenses, address _arbitrationLicenses, address payable _burnAddress) public
Stakable(_burnAddress)
{
INIT444(_userStore, _sellingLicenses, _arbitrationLicenses, _burnAddress);
}
function INIT444( //inject NONSTANDARD NAMING
address _userStore,
address _sellingLicenses,
address _arbitrationLicenses,
address payable _burnAddress
) public {
assert(_initialized == false);
_initialized = true;
userStore = UserStore(_userStore);
sellingLicenses = License(_sellingLicenses);
arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses);
burnAddress = _burnAddress;
basePrice = 0.01 ether;
_SETOWNER235(msg.sender);
}
function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING
UPDATECODEADDRESS579(newCode);
}
event LICENSESCHANGED569(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses); //inject NONSTANDARD NAMING
function SETLICENSES678( //inject NONSTANDARD NAMING
address _sellingLicenses,
address _arbitrationLicenses
) public ONLYOWNER677 {
emit LICENSESCHANGED569(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses));
sellingLicenses = License(_sellingLicenses);
arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses);
}
function ADDOFFER296( //inject NONSTANDARD NAMING
address _asset,
string memory _contactData,
string memory _location,
string memory _currency,
string memory _username,
uint[] memory _paymentMethods,
uint _limitL,
uint _limitU,
int16 _margin,
address payable _arbitrator
) public payable {
//require(sellingLicenses.isLicenseOwner(msg.sender), "Not a license owner");
// @TODO: limit number of offers if the sender is unlicensed?
require(arbitrationLicenses.ISALLOWED574(msg.sender, _arbitrator), "Arbitrator does not allow this transaction");
require(_limitL <= _limitU, "Invalid limits");
require(msg.sender != _arbitrator, "Cannot arbitrate own offers");
userStore.ADDORUPDATEUSER850(
msg.sender,
_contactData,
_location,
_username
);
Offer memory newOffer = Offer(
_margin,
_paymentMethods,
_limitL,
_limitU,
_asset,
_currency,
msg.sender,
_arbitrator,
false
);
uint256 offerId = offers.push(newOffer) - 1;
offerWhitelist[msg.sender][offerId] = true;
addressToOffers[msg.sender].push(offerId);
emit OFFERADDED246(
msg.sender,
offerId,
_asset,
_location,
_currency,
_username,
_paymentMethods,
_limitL,
_limitU,
_margin);
_STAKE330(offerId, msg.sender, _asset);
}
function REMOVEOFFER618(uint256 _offerId) external { //inject NONSTANDARD NAMING
require(offerWhitelist[msg.sender][_offerId], "Offer does not exist");
offers[_offerId].deleted = true;
offerWhitelist[msg.sender][_offerId] = false;
emit OFFERREMOVED496(msg.sender, _offerId);
_UNSTAKE786(_offerId);
}
function OFFER296(uint256 _id) external view returns ( //inject NONSTANDARD NAMING
address asset,
string memory currency,
int16 margin,
uint[] memory paymentMethods,
uint limitL,
uint limitU,
address payable owner,
address payable arbitrator,
bool deleted
) {
Offer memory theOffer = offers[_id];
// In case arbitrator rejects the seller
address payable offerArbitrator = theOffer.arbitrator;
if(!arbitrationLicenses.ISALLOWED574(theOffer.owner, offerArbitrator)){
offerArbitrator = address(0);
}
return (
theOffer.asset,
theOffer.currency,
theOffer.margin,
theOffer.paymentMethods,
theOffer.limitL,
theOffer.limitU,
theOffer.owner,
offerArbitrator,
theOffer.deleted
);
}
function GETOFFEROWNER81(uint256 _id) external view returns (address payable) { //inject NONSTANDARD NAMING
return (offers[_id].owner);
}
function GETASSET816(uint256 _id) external view returns (address) { //inject NONSTANDARD NAMING
return (offers[_id].asset);
}
function GETARBITRATOR107(uint256 _id) external view returns (address payable) { //inject NONSTANDARD NAMING
return (offers[_id].arbitrator);
}
function OFFERSSIZE507() external view returns (uint256) { //inject NONSTANDARD NAMING
return offers.length;
}
function GETOFFERIDS508(address _address) external view returns (uint256[] memory) { //inject NONSTANDARD NAMING
return addressToOffers[_address];
}
function SLASHSTAKE918(uint _offerId) external ONLYALLOWEDCONTRACTS234 { //inject NONSTANDARD NAMING
_SLASH319(_offerId);
}
function REFUNDSTAKE487(uint _offerId) external ONLYALLOWEDCONTRACTS234 { //inject NONSTANDARD NAMING
_REFUNDSTAKE66(_offerId);
}
}
contract Fees is Ownable, ReentrancyGuard, SafeTransfer {
address payable public feeDestination;
uint public feeMilliPercent;
mapping(address => uint) public feeTokenBalances;
mapping(uint => bool) public feePaid;
event FEEDESTINATIONCHANGED311(address payable); //inject NONSTANDARD NAMING
event FEEMILLIPERCENTCHANGED580(uint amount); //inject NONSTANDARD NAMING
event FEESWITHDRAWN828(uint amount, address token); //inject NONSTANDARD NAMING
constructor(address payable _feeDestination, uint _feeMilliPercent) public {
feeDestination = _feeDestination;
feeMilliPercent = _feeMilliPercent;
}
function SETFEEDESTINATIONADDRESS891(address payable _addr) external ONLYOWNER677 { //inject NONSTANDARD NAMING
feeDestination = _addr;
emit FEEDESTINATIONCHANGED311(_addr);
}
function SETFEEAMOUNT608(uint _feeMilliPercent) external ONLYOWNER677 { //inject NONSTANDARD NAMING
feeMilliPercent = _feeMilliPercent;
emit FEEMILLIPERCENTCHANGED580(_feeMilliPercent);
}
function _RELEASEFEE319(address payable _arbitrator, uint _value, address _tokenAddress, bool _isDispute) internal REENTRANCYGUARD399 { //inject NONSTANDARD NAMING
uint _milliPercentToArbitrator;
if (_isDispute) {
_milliPercentToArbitrator = 100000; // 100%
} else {
_milliPercentToArbitrator = 10000; // 10%
}
uint feeAmount = _GETVALUEOFFMILLIPERCENT932(_value, feeMilliPercent);
uint arbitratorValue = _GETVALUEOFFMILLIPERCENT932(feeAmount, _milliPercentToArbitrator);
uint destinationValue = feeAmount - arbitratorValue;
if (_tokenAddress != address(0)) {
ERC20Token tokenToPay = ERC20Token(_tokenAddress);
require(_SAFETRANSFER911(tokenToPay, _arbitrator, arbitratorValue), "Unsuccessful token transfer - arbitrator");
if (destinationValue > 0) {
require(_SAFETRANSFER911(tokenToPay, feeDestination, destinationValue), "Unsuccessful token transfer - destination");
}
} else {
// EIP1884 fix
(bool success, ) = _arbitrator.call.value(arbitratorValue)("");
require(success, "Transfer failed.");
if (destinationValue > 0) {
// EIP1884 fix
(bool success, ) = feeDestination.call.value(destinationValue)("");
require(success, "Transfer failed.");
}
}
}
function _GETVALUEOFFMILLIPERCENT932(uint _value, uint _milliPercent) internal pure returns(uint) { //inject NONSTANDARD NAMING
// To get the factor, we divide like 100 like a normal percent, but we multiply that by 1000 because it's a milliPercent
// Eg: 1 % = 1000 millipercent => Factor is 0.01, so 1000 divided by 100 * 1000
return (_value * _milliPercent) / (100 * 1000);
}
function _PAYFEE642(address _from, uint _id, uint _value, address _tokenAddress) internal { //inject NONSTANDARD NAMING
if (feePaid[_id]) return;
feePaid[_id] = true;
uint feeAmount = _GETVALUEOFFMILLIPERCENT932(_value, feeMilliPercent);
feeTokenBalances[_tokenAddress] += feeAmount;
if (_tokenAddress != address(0)) {
require(msg.value == 0, "Cannot send ETH with token address different from 0");
ERC20Token tokenToPay = ERC20Token(_tokenAddress);
require(_SAFETRANSFERFROM345(tokenToPay, _from, address(this), feeAmount + _value), "Unsuccessful token transfer");
} else {
require(msg.value == (_value + feeAmount), "ETH amount is required");
}
}
}
contract Arbitrable {
enum ArbitrationResult {UNSOLVED, BUYER, SELLER}
enum ArbitrationMotive {NONE, UNRESPONSIVE, PAYMENT_ISSUE, OTHER}
ArbitrationLicense public arbitratorLicenses;
mapping(uint => ArbitrationCase) public arbitrationCases;
address public fallbackArbitrator;
struct ArbitrationCase {
bool open;
address openBy;
address arbitrator;
uint arbitratorTimeout;
ArbitrationResult result;
ArbitrationMotive motive;
}
event ARBITRATORCHANGED687(address arbitrator); //inject NONSTANDARD NAMING
event ARBITRATIONCANCELED782(uint escrowId); //inject NONSTANDARD NAMING
event ARBITRATIONREQUIRED867(uint escrowId, uint timeout); //inject NONSTANDARD NAMING
event ARBITRATIONRESOLVED296(uint escrowId, ArbitrationResult result, address arbitrator); //inject NONSTANDARD NAMING
constructor(address _arbitratorLicenses, address _fallbackArbitrator) public {
arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses);
fallbackArbitrator = _fallbackArbitrator;
}
function _SOLVEDISPUTE500(uint _escrowId, bool _releaseFunds, address _arbitrator) internal; //inject NONSTANDARD NAMING
function _GETARBITRATOR209(uint _escrowId) internal view returns(address); //inject NONSTANDARD NAMING
function ISDISPUTED635(uint _escrowId) public view returns (bool) { //inject NONSTANDARD NAMING
return _ISDISPUTED184(_escrowId);
}
function _ISDISPUTED184(uint _escrowId) internal view returns (bool) { //inject NONSTANDARD NAMING
return arbitrationCases[_escrowId].open || arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED;
}
function HADDISPUTE385(uint _escrowId) public view returns (bool) { //inject NONSTANDARD NAMING
return arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED;
}
function CANCELARBITRATION839(uint _escrowId) external { //inject NONSTANDARD NAMING
require(arbitrationCases[_escrowId].openBy == msg.sender, "Arbitration can only be canceled by the opener");
require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && arbitrationCases[_escrowId].open,
"Arbitration already solved or not open");
delete arbitrationCases[_escrowId];
emit ARBITRATIONCANCELED782(_escrowId);
}
function _OPENDISPUTE139(uint _escrowId, address _openBy, uint8 _motive) internal { //inject NONSTANDARD NAMING
require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && !arbitrationCases[_escrowId].open,
"Arbitration already solved or has been opened before");
address arbitratorAddress = _GETARBITRATOR209(_escrowId);
require(arbitratorAddress != address(0), "Arbitrator is required");
uint timeout = block.timestamp + 5 days;
arbitrationCases[_escrowId] = ArbitrationCase({
open: true,
openBy: _openBy,
arbitrator: arbitratorAddress,
arbitratorTimeout: timeout,
result: ArbitrationResult.UNSOLVED,
motive: ArbitrationMotive(_motive)
});
emit ARBITRATIONREQUIRED867(_escrowId, timeout);
}
function SETARBITRATIONRESULT710(uint _escrowId, ArbitrationResult _result) external { //inject NONSTANDARD NAMING
require(arbitrationCases[_escrowId].open && arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED,
"Case must be open and unsolved");
require(_result != ArbitrationResult.UNSOLVED, "Arbitration does not have result");
require(arbitratorLicenses.ISLICENSEOWNER342(msg.sender), "Only arbitrators can invoke this function");
if (block.timestamp > arbitrationCases[_escrowId].arbitratorTimeout) {
require(arbitrationCases[_escrowId].arbitrator == msg.sender || msg.sender == fallbackArbitrator, "Invalid escrow arbitrator");
} else {
require(arbitrationCases[_escrowId].arbitrator == msg.sender, "Invalid escrow arbitrator");
}
arbitrationCases[_escrowId].open = false;
arbitrationCases[_escrowId].result = _result;
emit ARBITRATIONRESOLVED296(_escrowId, _result, msg.sender);
if(_result == ArbitrationResult.BUYER){
_SOLVEDISPUTE500(_escrowId, true, msg.sender);
} else {
_SOLVEDISPUTE500(_escrowId, false, msg.sender);
}
}
}
contract Escrow is IEscrow, Pausable, MessageSigned, Fees, Arbitrable, Proxiable {
EscrowTransaction[] public transactions;
address public relayer;
OfferStore public offerStore;
UserStore public userStore;
event CREATED284(uint indexed offerId, address indexed seller, address indexed buyer, uint escrowId); //inject NONSTANDARD NAMING
event FUNDED669(uint indexed escrowId, address indexed buyer, uint expirationTime, uint amount); //inject NONSTANDARD NAMING
event PAID949(uint indexed escrowId, address indexed seller); //inject NONSTANDARD NAMING
event RELEASED780(uint indexed escrowId, address indexed seller, address indexed buyer, address destination, bool isDispute); //inject NONSTANDARD NAMING
event CANCELED731(uint indexed escrowId, address indexed seller, address indexed buyer, bool isDispute); //inject NONSTANDARD NAMING
event RATING242(uint indexed offerId, address indexed participant, uint indexed escrowId, uint rating, bool ratingSeller); //inject NONSTANDARD NAMING
constructor(
address _relayer,
address _fallbackArbitrator,
address _arbitratorLicenses,
address _offerStore,
address _userStore,
address payable _feeDestination,
uint _feeMilliPercent)
Fees(_feeDestination, _feeMilliPercent)
Arbitrable(_arbitratorLicenses, _fallbackArbitrator)
public {
_initialized = true;
relayer = _relayer;
offerStore = OfferStore(_offerStore);
userStore = UserStore(_userStore);
}
function INIT444( //inject NONSTANDARD NAMING
address _fallbackArbitrator,
address _relayer,
address _arbitratorLicenses,
address _offerStore,
address _userStore,
address payable _feeDestination,
uint _feeMilliPercent
) external {
assert(_initialized == false);
_initialized = true;
fallbackArbitrator = _fallbackArbitrator;
arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses);
offerStore = OfferStore(_offerStore);
userStore = UserStore(_userStore);
relayer = _relayer;
feeDestination = _feeDestination;
feeMilliPercent = _feeMilliPercent;
paused = false;
_SETOWNER235(msg.sender);
}
function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING
UPDATECODEADDRESS579(newCode);
}
function SETRELAYER20(address _relayer) external ONLYOWNER677 { //inject NONSTANDARD NAMING
relayer = _relayer;
}
function SETFALLBACKARBITRATOR834(address _fallbackArbitrator) external ONLYOWNER677 { //inject NONSTANDARD NAMING
fallbackArbitrator = _fallbackArbitrator;
}
function SETARBITRATORLICENSE102(address _arbitratorLicenses) external ONLYOWNER677 { //inject NONSTANDARD NAMING
arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses);
}
function SETMETADATASTORE408(address _offerStore, address _userStore) external ONLYOWNER677 { //inject NONSTANDARD NAMING
offerStore = OfferStore(_offerStore);
userStore = UserStore(_userStore);
}
function _CREATETRANSACTION768( //inject NONSTANDARD NAMING
address payable _buyer,
address payable _destination,
uint _offerId,
uint _tokenAmount,
uint _fiatAmount
) internal WHENNOTPAUSED504 returns(uint escrowId)
{
address payable seller;
address payable arbitrator;
bool deleted;
address token;
(token, , , , , , seller, arbitrator, deleted) = offerStore.OFFER296(_offerId);
require(!deleted, "Offer is not valid");
require(seller != _buyer, "Seller and Buyer must be different");
require(arbitrator != _buyer && arbitrator != address(0), "Cannot buy offers where buyer is arbitrator");
require(_tokenAmount != 0 && _fiatAmount != 0, "Trade amounts cannot be 0");
escrowId = transactions.length++;
EscrowTransaction storage trx = transactions[escrowId];
trx.offerId = _offerId;
trx.token = token;
trx.buyer = _buyer;
trx.seller = seller;
trx.destination = _destination;
trx.arbitrator = arbitrator;
trx.tokenAmount = _tokenAmount;
trx.fiatAmount = _fiatAmount;
emit CREATED284(
_offerId,
seller,
_buyer,
escrowId
);
}
function CREATEESCROW324( //inject NONSTANDARD NAMING
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
address payable _destination,
string memory _contactData,
string memory _location,
string memory _username
) public returns(uint escrowId) {
userStore.ADDORUPDATEUSER850(msg.sender, _contactData, _location, _username);
escrowId = _CREATETRANSACTION768(msg.sender, _destination, _offerId, _tokenAmount, _fiatAmount);
}
function CREATEESCROW324( //inject NONSTANDARD NAMING
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
address payable _destination,
string memory _contactData,
string memory _location,
string memory _username,
uint _nonce,
bytes memory _signature
) public returns(uint escrowId) {
address payable _buyer = userStore.ADDORUPDATEUSER850(_signature, _contactData, _location, _username, _nonce);
escrowId = _CREATETRANSACTION768(_buyer, _destination, _offerId, _tokenAmount, _fiatAmount);
}
function CREATEESCROW_RELAYED829( //inject NONSTANDARD NAMING
address payable _sender,
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
address payable _destination,
string calldata _contactData,
string calldata _location,
string calldata _username
) external returns(uint escrowId) {
assert(msg.sender == relayer);
userStore.ADDORUPDATEUSER850(_sender, _contactData, _location, _username);
escrowId = _CREATETRANSACTION768(_sender, _destination, _offerId, _tokenAmount, _fiatAmount);
}
function FUND899(uint _escrowId) external payable WHENNOTPAUSED504 { //inject NONSTANDARD NAMING
_FUND192(msg.sender, _escrowId);
}
function _FUND192(address _from, uint _escrowId) internal WHENNOTPAUSED504 { //inject NONSTANDARD NAMING
require(transactions[_escrowId].seller == _from, "Only the seller can invoke this function");
require(transactions[_escrowId].status == EscrowStatus.CREATED, "Invalid escrow status");
transactions[_escrowId].expirationTime = block.timestamp + 5 days;
transactions[_escrowId].status = EscrowStatus.FUNDED;
uint tokenAmount = transactions[_escrowId].tokenAmount;
address token = transactions[_escrowId].token;
_PAYFEE642(_from, _escrowId, tokenAmount, token);
emit FUNDED669(_escrowId, transactions[_escrowId].buyer, block.timestamp + 5 days, tokenAmount);
}
function CREATEANDFUND840 ( //inject NONSTANDARD NAMING
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
string memory _bContactData,
string memory _bLocation,
string memory _bUsername,
uint _bNonce,
bytes memory _bSignature
) public payable returns(uint escrowId) {
address payable _buyer = userStore.ADDORUPDATEUSER850(_bSignature, _bContactData, _bLocation, _bUsername, _bNonce);
escrowId = _CREATETRANSACTION768(_buyer, _buyer, _offerId, _tokenAmount, _fiatAmount);
_FUND192(msg.sender, escrowId);
}
function _PAY687(address _sender, uint _escrowId) internal { //inject NONSTANDARD NAMING
EscrowTransaction storage trx = transactions[_escrowId];
require(trx.status == EscrowStatus.FUNDED, "Transaction is not funded");
require(trx.expirationTime > block.timestamp, "Transaction already expired");
require(trx.buyer == _sender, "Only the buyer can invoke this function");
trx.status = EscrowStatus.PAID;
emit PAID949(_escrowId, trx.seller);
}
function PAY204(uint _escrowId) external { //inject NONSTANDARD NAMING
_PAY687(msg.sender, _escrowId);
}
function PAY_RELAYED312(address _sender, uint _escrowId) external { //inject NONSTANDARD NAMING
assert(msg.sender == relayer);
_PAY687(_sender, _escrowId);
}
function PAYSIGNHASH991(uint _escrowId) public view returns(bytes32){ //inject NONSTANDARD NAMING
return keccak256(
abi.encodePacked(
address(this),
"pay(uint256)",
_escrowId
)
);
}
function PAY204(uint _escrowId, bytes calldata _signature) external { //inject NONSTANDARD NAMING
address sender = _RECOVERADDRESS15(_GETSIGNHASH525(PAYSIGNHASH991(_escrowId)), _signature);
_PAY687(sender, _escrowId);
}
function _RELEASE35(uint _escrowId, EscrowTransaction storage _trx, bool _isDispute) internal { //inject NONSTANDARD NAMING
require(_trx.status != EscrowStatus.RELEASED, "Already released");
_trx.status = EscrowStatus.RELEASED;
if(!_isDispute){
offerStore.REFUNDSTAKE487(_trx.offerId);
}
address token = _trx.token;
if(token == address(0)){
(bool success, ) = _trx.destination.call.value(_trx.tokenAmount)("");
require(success, "Transfer failed.");
} else {
require(_SAFETRANSFER911(ERC20Token(token), _trx.buyer, _trx.tokenAmount), "Couldn't transfer funds");
}
_RELEASEFEE319(_trx.arbitrator, _trx.tokenAmount, token, _isDispute);
emit RELEASED780(_escrowId, _trx.seller, _trx.buyer, _trx.destination, _isDispute);
}
function RELEASE349(uint _escrowId) external { //inject NONSTANDARD NAMING
EscrowStatus mStatus = transactions[_escrowId].status;
require(transactions[_escrowId].seller == msg.sender, "Only the seller can invoke this function");
require(mStatus == EscrowStatus.PAID || mStatus == EscrowStatus.FUNDED, "Invalid transaction status");
require(!_ISDISPUTED184(_escrowId), "Can't release a transaction that has an arbitration process");
_RELEASE35(_escrowId, transactions[_escrowId], false);
}
function CANCEL601(uint _escrowId) external WHENNOTPAUSED504 { //inject NONSTANDARD NAMING
EscrowTransaction storage trx = transactions[_escrowId];
EscrowStatus mStatus = trx.status;
require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED,
"Only transactions in created or funded state can be canceled");
require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function");
if(mStatus == EscrowStatus.FUNDED){
if(msg.sender == trx.seller){
require(trx.expirationTime < block.timestamp, "Can only be canceled after expiration");
}
}
_CANCEL322(_escrowId, trx, false);
}
// Same as cancel, but relayed by a contract so we get the sender as param
function CANCEL_RELAYED801(address _sender, uint _escrowId) external { //inject NONSTANDARD NAMING
assert(msg.sender == relayer);
EscrowTransaction storage trx = transactions[_escrowId];
EscrowStatus mStatus = trx.status;
require(trx.buyer == _sender, "Only the buyer can invoke this function");
require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED,
"Only transactions in created or funded state can be canceled");
_CANCEL322(_escrowId, trx, false);
}
function _CANCEL322(uint _escrowId, EscrowTransaction storage trx, bool isDispute) internal { //inject NONSTANDARD NAMING
EscrowStatus origStatus = trx.status;
require(trx.status != EscrowStatus.CANCELED, "Already canceled");
trx.status = EscrowStatus.CANCELED;
if (origStatus == EscrowStatus.FUNDED) {
address token = trx.token;
uint amount = trx.tokenAmount;
if (!isDispute) {
amount += _GETVALUEOFFMILLIPERCENT932(trx.tokenAmount, feeMilliPercent);
}
if (token == address(0)) {
(bool success, ) = trx.seller.call.value(amount)("");
require(success, "Transfer failed.");
} else {
ERC20Token erc20token = ERC20Token(token);
require(_SAFETRANSFER911(erc20token, trx.seller, amount), "Transfer failed");
}
}
trx.status = EscrowStatus.CANCELED;
emit CANCELED731(_escrowId, trx.seller, trx.buyer, isDispute);
}
function _RATETRANSACTION102(address _sender, uint _escrowId, uint _rate) internal { //inject NONSTANDARD NAMING
require(_rate >= 1, "Rating needs to be at least 1");
require(_rate <= 5, "Rating needs to be at less than or equal to 5");
EscrowTransaction storage trx = transactions[_escrowId];
require(trx.status == EscrowStatus.RELEASED || HADDISPUTE385(_escrowId), "Transaction not completed yet");
if (trx.buyer == _sender) {
require(trx.sellerRating == 0, "Transaction already rated");
emit RATING242(trx.offerId, trx.seller, _escrowId, _rate, true);
trx.sellerRating = _rate;
} else if (trx.seller == _sender) {
require(trx.buyerRating == 0, "Transaction already rated");
emit RATING242(trx.offerId, trx.buyer, _escrowId, _rate, false);
trx.buyerRating = _rate;
} else {
revert("Only participants can invoke this function");
}
}
function RATETRANSACTION74(uint _escrowId, uint _rate) external { //inject NONSTANDARD NAMING
_RATETRANSACTION102(msg.sender, _escrowId, _rate);
}
// Same as rateTransaction, but relayed by a contract so we get the sender as param
function RATETRANSACTION_RELAYED289(address _sender, uint _escrowId, uint _rate) external { //inject NONSTANDARD NAMING
assert(msg.sender == relayer);
_RATETRANSACTION102(_sender, _escrowId, _rate);
}
function GETBASICTRADEDATA166(uint _escrowId) //inject NONSTANDARD NAMING
external
view
returns(address payable buyer, address payable seller, address token, uint tokenAmount) {
buyer = transactions[_escrowId].buyer;
seller = transactions[_escrowId].seller;
tokenAmount = transactions[_escrowId].tokenAmount;
token = transactions[_escrowId].token;
return (buyer, seller, token, tokenAmount);
}
function OPENCASE508(uint _escrowId, uint8 _motive) external { //inject NONSTANDARD NAMING
EscrowTransaction storage trx = transactions[_escrowId];
require(!ISDISPUTED635(_escrowId), "Case already exist");
require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function");
require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions");
_OPENDISPUTE139(_escrowId, msg.sender, _motive);
}
function OPENCASE_RELAYED502(address _sender, uint256 _escrowId, uint8 _motive) external { //inject NONSTANDARD NAMING
assert(msg.sender == relayer);
EscrowTransaction storage trx = transactions[_escrowId];
require(!ISDISPUTED635(_escrowId), "Case already exist");
require(trx.buyer == _sender, "Only the buyer can invoke this function");
require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions");
_OPENDISPUTE139(_escrowId, _sender, _motive);
}
function OPENCASE508(uint _escrowId, uint8 _motive, bytes calldata _signature) external { //inject NONSTANDARD NAMING
EscrowTransaction storage trx = transactions[_escrowId];
require(!ISDISPUTED635(_escrowId), "Case already exist");
require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions");
address senderAddress = _RECOVERADDRESS15(_GETSIGNHASH525(OPENCASESIGNHASH754(_escrowId, _motive)), _signature);
require(trx.buyer == senderAddress || trx.seller == senderAddress, "Only participants can invoke this function");
_OPENDISPUTE139(_escrowId, msg.sender, _motive);
}
function _SOLVEDISPUTE500(uint _escrowId, bool _releaseFunds, address _arbitrator) internal { //inject NONSTANDARD NAMING
EscrowTransaction storage trx = transactions[_escrowId];
require(trx.buyer != _arbitrator && trx.seller != _arbitrator, "Arbitrator cannot be part of transaction");
if (_releaseFunds) {
_RELEASE35(_escrowId, trx, true);
offerStore.SLASHSTAKE918(trx.offerId);
} else {
_CANCEL322(_escrowId, trx, true);
_RELEASEFEE319(trx.arbitrator, trx.tokenAmount, trx.token, true);
}
}
function _GETARBITRATOR209(uint _escrowId) internal view returns(address) { //inject NONSTANDARD NAMING
return transactions[_escrowId].arbitrator;
}
function OPENCASESIGNHASH754(uint _escrowId, uint8 _motive) public view returns(bytes32){ //inject NONSTANDARD NAMING
return keccak256(
abi.encodePacked(
address(this),
"openCase(uint256)",
_escrowId,
_motive
)
);
}
function RECEIVEAPPROVAL139(address _from, uint256 _amount, address _token, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_token == address(msg.sender), "Wrong call");
require(_data.length == 36, "Wrong data length");
bytes4 sig;
uint256 escrowId;
(sig, escrowId) = _ABIDECODEFUNDCALL446(_data);
if (sig == bytes4(0xca1d209d)){ // fund(uint256)
uint tokenAmount = transactions[escrowId].tokenAmount;
require(_amount == tokenAmount + _GETVALUEOFFMILLIPERCENT932(tokenAmount, feeMilliPercent), "Invalid amount");
_FUND192(_from, escrowId);
} else {
revert("Wrong method selector");
}
}
function _ABIDECODEFUNDCALL446(bytes memory _data) internal pure returns (bytes4 sig, uint256 escrowId) { //inject NONSTANDARD NAMING
assembly {
sig := mload(add(_data, add(0x20, 0)))
escrowId := mload(add(_data, 36))
}
}
function WITHDRAW_EMERGENCY162(uint _escrowId) external WHENPAUSED494 { //inject NONSTANDARD NAMING
EscrowTransaction storage trx = transactions[_escrowId];
require(trx.status == EscrowStatus.FUNDED, "Cannot withdraw from escrow in a stage different from FUNDED. Open a case");
_CANCEL322(_escrowId, trx, false);
}
}
|
inject NONSTANDARD NAMING
|
function TRANSFEROWNERSHIP770(address _newOwner) external ONLYOWNER677 {
| 12,593,798 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
}
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
}
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
if (totalBorrowsETH == 0) return uint256(0);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
// Pack the struct data
(uint[4] memory numData, address[6] memory cAddresses, bytes memory callData)
= _packData(_createInfo, _exchangeData);
bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
function _packData(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) {
numData = [
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
cAddresses = [
_createInfo.cCollAddress,
_createInfo.cBorrowAddress,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
callData = exchangeData.callData;
}
}
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
}
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CreamSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the cream position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
contract DFSExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract DFSPrices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers,
bytes[] memory _additionalData
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
}
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
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);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscriptions {
function unsubscribe() external virtual ;
}
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
abstract contract TokenInterface {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
}
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
contract MCDCreateTaker {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
contract MCDSaverProxyHelper is DSMath {
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
}
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getAccountBalances(
Account.Info memory account
) public view virtual returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function setOperators(
OperatorArg[] memory args
) public virtual;
function getNumMarkets() public view virtual returns (uint256);
function getMarketTokenAddress(uint256 marketId)
public
view
virtual
returns (address);
}
library Account {
// ============ Enums ============
/*
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum Status {
Normal,
Liquid,
Vapor
}
// ============ Structs ============
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
// The complete storage for any account
struct Storage {
mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
// ============ Library Functions ============
function equals(
Info memory a,
Info memory b
)
internal
pure
returns (bool)
{
return a.owner == b.owner && a.number == b.number;
}
}
library Actions {
// ============ Constants ============
bytes32 constant FILE = "Actions";
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {
OnePrimary,
TwoPrimary,
PrimaryAndSecondary
}
enum MarketLayout {
ZeroMarkets,
OneMarket,
TwoMarkets
}
// ============ Structs ============
/*
* Arguments that are passed to Solo in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
// ============ Action Types ============
/*
* Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply.
*/
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
/*
* Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount
* previously supplied.
*/
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
/*
* Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
* The amount field applies to accountOne.
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
/*
* Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
* applies to the makerMarket.
*/
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
* to the takerMarket.
*/
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Trades balances between two accounts using any external contract that implements the
* AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
* which it is trading on-behalf-of). The amount field applies to the makerAccount and the
* inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
* quote a change for the makerAccount in the outputMarket (or will disallow the trade).
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
/*
* Each account must maintain a certain margin-ratio (specified globally). If the account falls
* below this margin-ratio, it can be liquidated by any other account. This allows anyone else
* (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
* exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
* by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
* account also sets a flag on the account that the account is being liquidated. This allows
* anyone to continue liquidating the account until there are no more borrows being taken by the
* liquidating account. Liquidators do not have to liquidate the entire account all at once but
* can liquidate as much as they choose. The liquidating flag allows liquidators to continue
* liquidating the account even if it becomes collateralized through partial liquidation or
* price movement.
*/
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Similar to liquidate, but vaporAccounts are accounts that have only negative balances
* remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in
* exchange for a collateral asset (heldMarket) at a favorable spread. However, since the
* liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens.
*/
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Passes arbitrary bytes of data to an external contract that implements the Callee interface.
* Does not change any asset amounts. This function may be useful for setting certain variables
* on layer-two contracts for certain accounts without having to make a separate Ethereum
* transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
* from an operator of the particular account.
*/
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
// ============ Helper Functions ============
function getMarketLayout(
ActionType actionType
)
internal
pure
returns (MarketLayout)
{
if (
actionType == Actions.ActionType.Deposit
|| actionType == Actions.ActionType.Withdraw
|| actionType == Actions.ActionType.Transfer
) {
return MarketLayout.OneMarket;
}
else if (actionType == Actions.ActionType.Call) {
return MarketLayout.ZeroMarkets;
}
return MarketLayout.TwoMarkets;
}
function getAccountLayout(
ActionType actionType
)
internal
pure
returns (AccountLayout)
{
if (
actionType == Actions.ActionType.Transfer
|| actionType == Actions.ActionType.Trade
) {
return AccountLayout.TwoPrimary;
} else if (
actionType == Actions.ActionType.Liquidate
|| actionType == Actions.ActionType.Vaporize
) {
return AccountLayout.PrimaryAndSecondary;
}
return AccountLayout.OnePrimary;
}
// ============ Parsing Functions ============
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
{
assert(args.actionType == ActionType.Deposit);
return DepositArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
from: args.otherAddress
});
}
function parseWithdrawArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (WithdrawArgs memory)
{
assert(args.actionType == ActionType.Withdraw);
return WithdrawArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
to: args.otherAddress
});
}
function parseTransferArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TransferArgs memory)
{
assert(args.actionType == ActionType.Transfer);
return TransferArgs({
amount: args.amount,
accountOne: accounts[args.accountId],
accountTwo: accounts[args.otherAccountId],
market: args.primaryMarketId
});
}
function parseBuyArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (BuyArgs memory)
{
assert(args.actionType == ActionType.Buy);
return BuyArgs({
amount: args.amount,
account: accounts[args.accountId],
makerMarket: args.primaryMarketId,
takerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseSellArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (SellArgs memory)
{
assert(args.actionType == ActionType.Sell);
return SellArgs({
amount: args.amount,
account: accounts[args.accountId],
takerMarket: args.primaryMarketId,
makerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseTradeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TradeArgs memory)
{
assert(args.actionType == ActionType.Trade);
return TradeArgs({
amount: args.amount,
takerAccount: accounts[args.accountId],
makerAccount: accounts[args.otherAccountId],
inputMarket: args.primaryMarketId,
outputMarket: args.secondaryMarketId,
autoTrader: args.otherAddress,
tradeData: args.data
});
}
function parseLiquidateArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (LiquidateArgs memory)
{
assert(args.actionType == ActionType.Liquidate);
return LiquidateArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
liquidAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseVaporizeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (VaporizeArgs memory)
{
assert(args.actionType == ActionType.Vaporize);
return VaporizeArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
vaporAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseCallArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (CallArgs memory)
{
assert(args.actionType == ActionType.Call);
return CallArgs({
account: accounts[args.accountId],
callee: args.otherAddress,
data: args.data
});
}
}
library Math {
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Math";
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint128"
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint96"
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint32"
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
library Types {
using Math for uint256;
// ============ AssetAmount ============
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;
}
// ============ Par (Principal Amount) ============
// Total borrow and supply values for a market
struct TotalPar {
uint128 borrow;
uint128 supply;
}
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
function zeroWei()
internal
pure
returns (Wei memory)
{
return Wei({
sign: false,
value: 0
});
}
function sub(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
return add(a, negative(b));
}
function add(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
Wei memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value);
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value);
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value);
}
}
return result;
}
function equals(
Wei memory a,
Wei memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Wei memory a
)
internal
pure
returns (Wei memory)
{
return Wei({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Wei memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Wei memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Wei memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// 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);
}
}
}
}
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
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: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
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: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
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: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 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(ERC20 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));
}
function _callOptionalReturn(ERC20 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");
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for variable rate and 2 for fixed rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
if (originationFee > 0) {
ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee);
}
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 19;
uint public BOOST_GAS_TOKEN = 19;
uint public MAX_GAS_PRICE = 200000000000; // 200 gwei
uint public REPAY_GAS_COST = 2500000;
uint public BOOST_GAS_COST = 2500000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address user,
address proxy
)
= abi.decode(data, (address,address,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
}
// pull tokens from user to proxy
ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x7b856af5753a9f80968EA002641E69AdF1d795aB;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve AaveImport to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
contract CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint) {
uint compBalance = 0;
for(uint i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) {
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta);
}
function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) {
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta);
}
}
}
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CompoundImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, 0);
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay compound debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the cream protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the cream protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the cream protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the cream market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the cream market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CreamLoanInfo is CreamSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches cream prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches cream collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay cream debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return address(this).balance;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (_exData.srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
}
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.offchainData.callData, 36, _exData.destAmount);
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
if (success) {
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1800000;
uint public BOOST_GAS_COST = 1800000;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
closeCDP(closeData, exchangeData, user);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user
) internal {
paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = _closeData.daiAmount;
(, daiSwaped) = _buy(_exchangeData);
}
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
manager.frob(_cdpId, -toPositiveInt(_amount), 0);
manager.flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = manager.urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDCloseTaker is MCDSaverProxyHelper {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
manager.urns(_closeData.cdpId),
manager.urns(_closeData.cdpId),
manager.ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId));
}
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public constant manager = Manager(MANAGER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(_cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(_cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(manager.urns(_cdpId));
uint maxAmount = getMaxDebt(_cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
manager.move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
manager.ilks(_cdpId),
manager.urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
manager.frob(_cdpId, -toPositiveInt(frobAmount), 0);
manager.flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = manager.urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) {
address urn = manager.urns(_cdpId);
ilk = manager.ilks(_cdpId);
(collateral, debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
price = getPrice(ilk);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (feeAmount > _amount / 10) {
feeAmount = _amount / 10;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
return feeAmount;
}
return 0;
}
}
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (isEthJoinAddr(_joinAddr)
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth {
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
if (paramData.swapType == 1) { // COLL_SWAP
exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) { // DEBT_SWAP
exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy);
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)));
} else { // NO_SWAP just send tokens to proxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr));
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(uint _amount, uint _fee, bytes memory _params)
internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) {
(
uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x
address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper
uint8[3] memory enumData, // fromProtocol, toProtocol, swapType
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address));
bytes memory proxyData1;
bytes memory proxyData2;
uint openDebtAmount = (_amount + _fee);
if (enumData[0] == 0) { // MAKER FROM
proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]);
} else if(enumData[0] == 1) { // COMPOUND FROM
if (enumData[2] == 2) { // DEBT_SWAP
proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]);
} else {
proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]);
}
}
if (enumData[1] == 0) { // MAKER TO
proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount);
} else if(enumData[1] == 1) { // COMPOUND TO
if (enumData[2] == 2) { // DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]);
} else {
proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: addrData[2],
protocol1: enumData[0],
protocol2: enumData[1],
swapType: enumData[2]
});
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: addrData[4],
destAddr: addrData[5],
srcAmount: numData[4],
destAmount: numData[5],
minPrice: numData[6],
wrapper: addrData[7],
exchangeAddr: addrData[6],
callData: callData,
price0x: numData[7]
});
}
function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxyInterface proxy = DSProxyInterface(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
(
uint[8] memory numData,
address[8] memory addrData,
uint8[3] memory enumData,
bytes memory callData
)
= _packData(_loanShift, _exchangeData);
// encode data
bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return CTokenInterface(_address).underlying();
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function logEvent(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
function _packData(
LoanShiftData memory _loanShift,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) {
numData = [
_loanShift.collAmount,
_loanShift.debtAmount,
_loanShift.id1,
_loanShift.id2,
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
addrData = [
_loanShift.addrLoan1,
_loanShift.addrLoan2,
_loanShift.debtAddr1,
_loanShift.debtAddr2,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
enumData = [
uint8(_loanShift.fromProtocol),
uint8(_loanShift.toProtocol),
uint8(_loanShift.swapType)
];
callData = exchangeData.callData;
}
}
contract CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
contract McdShifter is MCDSaverProxy {
using SafeERC20 for ERC20;
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(_cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawCollateral(_cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(_cdpId, _joinAddr, collAmount);
// draw debt
drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
}
contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
// swap
(, destAmount) = _sell(_data);
destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr);
// swap
(, destAmount) = _sell(_data);
} else {
_data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr);
destAmount = _data.srcAmount;
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
(, uint sellAmount) = _sell(exchangeData);
getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
(
uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x
address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[4],address[6],bytes,address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
cAddresses[0], cAddresses[1], (_amount + _fee));
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: cAddresses[2],
destAddr: cAddresses[3],
srcAmount: numData[0],
destAmount: numData[1],
minPrice: numData[2],
wrapper: cAddresses[5],
exchangeAddr: cAddresses[4],
callData: callData,
price0x: numData[3]
});
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: cAddresses[0],
cDebtAddr: cAddresses[1]
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxy proxy = DSProxy(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.srcAmount = collAmount;
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId));
uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
bytes32 ilk = manager.ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(_saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
|
Format the call data for DSProxy Send Flash loan amount to DSProxy Execute the Close/Change debt operation Send extra to DSProxy
|
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(ParamData memory paramData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
sendToProxy(payable(paramData.proxy), _reserve, _amount);
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy);
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)));
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr));
}
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
| 7,334,329 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "../metatx/ERC2771Context.sol";
import "../interfaces/ITokenManager.sol";
contract TokenManager is ITokenManager, ERC2771Context, Ownable, Pausable {
mapping(address => TokenInfo) public tokensInfo;
event FeeChanged(address indexed tokenAddress, uint256 indexed equilibriumFee, uint256 indexed maxFee);
modifier tokenChecks(address tokenAddress) {
require(tokenAddress != address(0), "Token address cannot be 0");
require(tokensInfo[tokenAddress].supportedToken, "Token not supported");
_;
}
/**
* First key is toChainId and second key is token address being deposited on current chain
*/
mapping(uint256 => mapping(address => TokenConfig)) public depositConfig;
/**
* Store min/max amount of token to transfer based on token address
*/
mapping(address => TokenConfig) public transferConfig;
constructor(address trustedForwarder) ERC2771Context(trustedForwarder) {
// Empty Constructor
}
function getEquilibriumFee(address tokenAddress) public view override returns (uint256) {
return tokensInfo[tokenAddress].equilibriumFee;
}
function getMaxFee(address tokenAddress) public view override returns (uint256) {
return tokensInfo[tokenAddress].maxFee;
}
function changeFee(
address tokenAddress,
uint256 _equilibriumFee,
uint256 _maxFee
) external override onlyOwner whenNotPaused {
require(_equilibriumFee != 0, "Equilibrium Fee cannot be 0");
require(_maxFee != 0, "Max Fee cannot be 0");
tokensInfo[tokenAddress].equilibriumFee = _equilibriumFee;
tokensInfo[tokenAddress].maxFee = _maxFee;
emit FeeChanged(tokenAddress, tokensInfo[tokenAddress].equilibriumFee, tokensInfo[tokenAddress].maxFee);
}
function setTokenTransferOverhead(address tokenAddress, uint256 gasOverhead)
external
tokenChecks(tokenAddress)
onlyOwner
{
tokensInfo[tokenAddress].transferOverhead = gasOverhead;
}
/**
* Set DepositConfig for the given combination of toChainId, tokenAddress.
* This is used while depositing token in Liquidity Pool. Based on the destination chainid
* min and max deposit amount is checked.
*/
function setDepositConfig(
uint256[] memory toChainId,
address[] memory tokenAddresses,
TokenConfig[] memory tokenConfig
) external onlyOwner {
require(
(toChainId.length == tokenAddresses.length) && (tokenAddresses.length == tokenConfig.length),
" ERR_ARRAY_LENGTH_MISMATCH"
);
for (uint256 index = 0; index < tokenConfig.length; ++index) {
depositConfig[toChainId[index]][tokenAddresses[index]].min = tokenConfig[index].min;
depositConfig[toChainId[index]][tokenAddresses[index]].max = tokenConfig[index].max;
}
}
function addSupportedToken(
address tokenAddress,
uint256 minCapLimit,
uint256 maxCapLimit,
uint256 equilibriumFee,
uint256 maxFee
) external onlyOwner {
require(tokenAddress != address(0), "Token address cannot be 0");
require(maxCapLimit > minCapLimit, "maxCapLimit > minCapLimit");
tokensInfo[tokenAddress].supportedToken = true;
transferConfig[tokenAddress].min = minCapLimit;
transferConfig[tokenAddress].max = maxCapLimit;
tokensInfo[tokenAddress].tokenConfig = transferConfig[tokenAddress];
tokensInfo[tokenAddress].equilibriumFee = equilibriumFee;
tokensInfo[tokenAddress].maxFee = maxFee;
}
function removeSupportedToken(address tokenAddress) external tokenChecks(tokenAddress) onlyOwner {
tokensInfo[tokenAddress].supportedToken = false;
}
function updateTokenCap(
address tokenAddress,
uint256 minCapLimit,
uint256 maxCapLimit
) external tokenChecks(tokenAddress) onlyOwner {
require(maxCapLimit > minCapLimit, "maxCapLimit > minCapLimit");
transferConfig[tokenAddress].min = minCapLimit;
transferConfig[tokenAddress].max = maxCapLimit;
}
function getTokensInfo(address tokenAddress) public view override returns (TokenInfo memory) {
TokenInfo memory tokenInfo = TokenInfo(
tokensInfo[tokenAddress].transferOverhead,
tokensInfo[tokenAddress].supportedToken,
tokensInfo[tokenAddress].equilibriumFee,
tokensInfo[tokenAddress].maxFee,
transferConfig[tokenAddress]
);
return tokenInfo;
}
function getDepositConfig(uint256 toChainId, address tokenAddress)
public
view
override
returns (TokenConfig memory)
{
return depositConfig[toChainId][tokenAddress];
}
function getTransferConfig(address tokenAddress) public view override returns (TokenConfig memory) {
return transferConfig[tokenAddress];
}
function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) {
return ERC2771Context._msgSender();
}
function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {
return ERC2771Context._msgData();
}
}
|
Set DepositConfig for the given combination of toChainId, tokenAddress. This is used while depositing token in Liquidity Pool. Based on the destination chainid min and max deposit amount is checked./
|
function setDepositConfig(
uint256[] memory toChainId,
address[] memory tokenAddresses,
TokenConfig[] memory tokenConfig
) external onlyOwner {
require(
(toChainId.length == tokenAddresses.length) && (tokenAddresses.length == tokenConfig.length),
" ERR_ARRAY_LENGTH_MISMATCH"
);
for (uint256 index = 0; index < tokenConfig.length; ++index) {
depositConfig[toChainId[index]][tokenAddresses[index]].min = tokenConfig[index].min;
depositConfig[toChainId[index]][tokenAddresses[index]].max = tokenConfig[index].max;
}
}
| 965,293 |
pragma solidity ^0.4.24;
import "zos-lib/contracts/Initializable.sol";
import "openzeppelin-eth/contracts/math/SafeMath.sol";
import "openzeppelin-eth/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-eth/contracts/token/ERC20/SafeERC20.sol";
/**
* @title Vouching
* @dev Contract for staking tokens to back entries.
*/
contract Vouching is Initializable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
uint256 public constant PCT_BASE = 10 ** 18; // 100e16 = 100%;
uint256 public constant MAX_CHALLENGE_FEE = 50 * 10 ** 16; // 50e16 = 50%;
uint256 public constant MAX_VOUCHERS = 230;
uint256 public constant ANSWER_WINDOW = 7 days;
uint256 public constant APPEAL_WINDOW = 9 days;
event OwnershipTransferred(uint256 indexed id, address indexed oldOwner, address indexed newOwner);
event AppealsResolutionTransferred(address indexed oldAppealsResolver, address indexed newAppealsResolver);
event Vouched(uint256 indexed id, address indexed sender, uint256 amount);
event Unvouched(uint256 indexed id, address indexed sender, uint256 amount);
event Registered(uint256 indexed id, address indexed addr, address owner, uint256 minimumStake, string metadataURI, bytes32 metadataHash);
event Challenged(uint256 indexed id, uint256 indexed challengeID, address indexed challenger, uint256 amount, string metadataURI, bytes32 metadataHash);
event Accepted(uint256 indexed challengeID);
event Rejected(uint256 indexed challengeID);
event Confirmed(uint256 indexed challengeID);
event Appealed(uint256 indexed challengeID, address indexed appealer, uint256 amount);
event AppealAffirmed(uint256 indexed challengeID, address indexed appealsResolver);
event AppealDismissed(uint256 indexed challengeID, address indexed appealsResolver);
event AppealFeeChanged(uint256 oldAppealFee, uint256 newAppealFee, address appealsResolver);
event MinimumStakeChanged(uint256 oldMinimumStake, uint256 newMinimumStake, address appealsResolver);
enum Answer { PENDING, ACCEPTED, REJECTED }
enum Resolution { PENDING, APPEAL_AFFIRMED, APPEAL_DISMISSED, CONFIRMED }
struct Entry {
uint256 id;
address addr;
address owner;
string metadataURI;
bytes32 metadataHash;
uint256 minimumStake;
uint256 totalVouched;
uint256 totalAvailable;
address[] vouchersAddress;
mapping (address => Voucher) vouchers;
mapping (address => uint256) vouchersAddressIndex;
}
struct Voucher {
address addr;
uint256 vouched;
uint256 available;
mapping (uint256 => uint256) blockedPerChallenge;
}
struct Challenge {
uint256 id;
uint256 entryID;
address challenger;
uint256 amount;
uint256 createdAt;
string metadataURI;
bytes32 metadataHash;
uint256 answeredAt;
Answer answer;
Appeal appeal;
Resolution resolution;
}
struct Appeal {
address appealer;
uint256 amount;
uint256 createdAt;
}
ERC20 private token_;
uint256 private appealFee_;
uint256 private minimumStake_;
address private appealsResolver_;
Entry[] private entries_;
Challenge[] private challenges_;
modifier existingEntry(uint256 _entryID) {
require(_existsEntry(_entryID), "Could not find a vouched entry with the given ID");
_;
}
modifier existingChallenge(uint256 _challengeID) {
require(_existsChallenge(_challengeID), "Could not find a challenge with the given ID");
_;
}
modifier onlyAppealsResolver() {
require(msg.sender == appealsResolver_, "Given method can only be called by the appealsResolver");
_;
}
/**
* @dev Initializer function. Called only once when a proxy for the contract is created.
* @param _minimumStake uint256 that defines the minimum initial amount of vouched tokens a dependency can have when being created.
* @param _token ERC20 token to be used for vouching on dependencies.
*/
function initialize(ERC20 _token, uint256 _minimumStake, uint256 _appealFee, address _appealsResolver) initializer public {
require(_token != address(0), "The token address cannot be zero");
require(_appealsResolver != address(0), "The appeals resolver address cannot be zero");
token_ = _token;
appealFee_ = _appealFee;
minimumStake_ = _minimumStake;
appealsResolver_ = _appealsResolver;
}
/**
* @dev Tells the the initial minimum amount of vouched tokens a dependency can have when being created.
* @return A uint256 number with the minimumStake value.
*/
function minimumStake() public view returns(uint256) {
return minimumStake_;
}
/**
* @dev Sets the minimum stake, can only be called by the appeals resolver.
*/
function setMinimumStake(uint256 _minimumStake) public onlyAppealsResolver {
emit MinimumStakeChanged(minimumStake_, _minimumStake, appealsResolver_);
minimumStake_ = _minimumStake;
}
/**
* @dev Tells the ERC20 token being used for vouching.
* @return The address of the ERC20 token being used for vouching.
*/
function token() public view returns(ERC20) {
return token_;
}
/**
* @dev Tells the appeal payout fee.
* @return The appeal payout fee.
*/
function appealFee() public view returns(uint256) {
return appealFee_;
}
/**
* @dev Sets the appeal payout fee, can only be called by the appeals resolver.
*/
function setAppealFee(uint256 _appealFee) onlyAppealsResolver public {
emit AppealFeeChanged(appealFee_, _appealFee, appealsResolver_);
appealFee_ = _appealFee;
}
/**
* @dev Tells the address of the appeals resolver.
* @return The address of the appeals resolver in charge of the vouching contract.
*/
function appealsResolver() public view returns(address) {
return appealsResolver_;
}
/**
* @dev Tells the information associated to an entry
*/
function getEntry(uint256 _entryID)
public view returns (
address addr,
address owner,
string metadataURI,
bytes32 metadataHash,
uint256 minimumStake,
uint256 totalVouched,
uint256 totalAvailable,
uint256 totalBlocked
)
{
if (!_existsEntry(_entryID)) return (address(0), address(0), "", bytes32(0), uint256(0), uint256(0), uint256(0), uint256(0));
Entry storage e = entries_[_entryID];
uint256 _totalBlocked = e.totalVouched.sub(e.totalAvailable);
return (e.addr, e.owner, e.metadataURI, e.metadataHash, e.minimumStake, e.totalVouched, e.totalAvailable, _totalBlocked);
}
/**
* @dev Tells the information associated to a challenge
*/
function getChallenge(uint256 _challengeID)
public view returns (
uint256 entryID,
address challenger,
uint256 amount,
uint256 createdAt,
string metadataURI,
bytes32 metadataHash,
Answer answer,
uint256 answeredAt,
Resolution resolution
)
{
if (!_existsChallenge(_challengeID)) return (uint256(0), address(0), uint256(0), uint256(0), "", bytes32(0), Answer.PENDING, uint256(0), Resolution.PENDING);
Challenge storage c = challenges_[_challengeID];
return (c.entryID, c.challenger, c.amount, c.createdAt, c.metadataURI, c.metadataHash, c.answer, c.answeredAt, c.resolution);
}
/**
* @dev Tells the information associated to a challenge's appeal
*/
function getAppeal(uint256 _challengeID) public view returns (address appealer, uint256 amount, uint256 createdAt) {
if (!_existsChallenge(_challengeID)) return (address(0), uint256(0), uint256(0));
Appeal storage a = challenges_[_challengeID].appeal;
return (a.appealer, a.amount, a.createdAt);
}
/**
* @dev Tells the vouched, available and blocked amounts of a voucher for an entry
*/
function getVouched(uint256 _entryID, address _voucher) public view returns (uint256 vouched, uint256 available, uint256 blocked) {
if (!_existsEntry(_entryID)) return (uint256(0), uint256(0), uint256(0));
uint256 _vouchedAmount = _vouched(_entryID, _voucher);
uint256 _availableAmount = _available(_entryID, _voucher);
return (_vouchedAmount, _availableAmount, _vouchedAmount.sub(_availableAmount));
}
/**
* @dev Transfers the ownership of a given entry
*/
function transferOwnership(uint256 _entryID, address _newOwner) public existingEntry(_entryID) {
require(_newOwner != address(0), "New owner address cannot be zero");
require(_isOwner(msg.sender, _entryID), "Transfer ownership can only be called by the owner of the entry");
entries_[_entryID].owner = _newOwner;
emit OwnershipTransferred(_entryID, msg.sender, _newOwner);
}
/**
* @dev Transfers the appeals resolution to another address
*/
function transferAppealsResolution(address _newAppealsResolver) public onlyAppealsResolver {
require(_newAppealsResolver != address(0), "New appeals resolver address cannot be zero");
appealsResolver_ = _newAppealsResolver;
emit AppealsResolutionTransferred(msg.sender, _newAppealsResolver);
}
/**
* @dev Generates a fresh ID and adds a new `vouched` entry to the vouching contract, owned by the sender, with `amount`
* initial ZEP tokens sent by the sender. Requires vouching at least `minStake` tokens, which is a constant value.
*/
function register(address _addr, uint256 _amount, string _metadataURI, bytes32 _metadataHash) public {
require(_addr != address(0), "Entry address cannot be zero");
require(_amount >= minimumStake_, "Initial vouched amount must be equal to or greater than the minimum stake");
uint256 _entryID = entries_.length++;
uint256 _vouchedAmount = _amount.sub(minimumStake_);
Entry storage entry_ = entries_[_entryID];
entry_.id = _entryID;
entry_.addr = _addr;
entry_.owner = msg.sender;
entry_.metadataURI = _metadataURI;
entry_.metadataHash = _metadataHash;
entry_.minimumStake = minimumStake_;
entry_.totalVouched = _vouchedAmount;
entry_.totalAvailable = _vouchedAmount;
emit Registered(_entryID, _addr, msg.sender, minimumStake_, _metadataURI, _metadataHash);
if (_vouchedAmount > 0) _vouch(entry_, msg.sender, _vouchedAmount);
token_.safeTransferFrom(msg.sender, this, _amount);
}
/**
* @dev Increases the vouch for the package identified by `id` by `amount` for `sender`.
*/
function vouch(uint256 _entryID, uint256 _amount) public existingEntry(_entryID) {
require(_amount > 0, "The amount of tokens to be vouched must be greater than zero");
Entry storage entry_ = entries_[_entryID];
entry_.totalVouched = entry_.totalVouched.add(_amount);
entry_.totalAvailable = entry_.totalAvailable.add(_amount);
_vouch(entry_, msg.sender, _amount);
token_.safeTransferFrom(msg.sender, this, _amount);
}
/**
* @dev Decreases the vouch for the package identified by `id` by `amount` for `sender`. Note that if `sender` is the
* `vouched` owner, he cannot decrease his vouching under `minStake`.
*/
function unvouch(uint256 _entryID, uint256 _amount) public existingEntry(_entryID) {
require(_amount > 0, "The amount of tokens to be unvouched must be greater than zero");
require(_amount <= _available(_entryID, msg.sender), "The amount of tokens to be unvouched cannot be granter than your unblocked amount");
Entry storage entry_ = entries_[_entryID];
entry_.totalVouched = entry_.totalVouched.sub(_amount);
entry_.totalAvailable = entry_.totalAvailable.sub(_amount);
Voucher storage voucher_ = entry_.vouchers[msg.sender];
voucher_.vouched = voucher_.vouched.sub(_amount);
voucher_.available = voucher_.available.sub(_amount);
if (voucher_.vouched == 0) _removeVoucher(entry_, msg.sender);
emit Unvouched(_entryID, msg.sender, _amount);
token_.safeTransfer(msg.sender, _amount);
}
/**
* @dev Creates a new challenge with a fresh id in a _pending_ state towards a package for an `amount` of tokens,
* where the details of the challenge are in the URI specified.
*/
function challenge(uint256 _entryID, uint256 _fee, string _metadataURI, bytes32 _metadataHash) public existingEntry(_entryID) {
Entry storage entry_ = entries_[_entryID];
require(entry_.totalAvailable > 0, "Given entry does not have an available amount");
require(_fee <= MAX_CHALLENGE_FEE, "The challenge fee must be lower than or equal to 50% (50e16)");
require(!_isOwner(msg.sender, _entryID), "Vouched entries cannot be challenged by their owner");
uint256 _amount = entry_.totalAvailable.mul(_fee).div(PCT_BASE);
entry_.totalAvailable = entry_.totalAvailable.sub(_amount);
uint256 _challengeID = challenges_.length++;
Challenge storage challenge_ = challenges_[_challengeID];
challenge_.id = _challengeID;
challenge_.entryID = _entryID;
challenge_.amount = _amount;
challenge_.createdAt = now;
challenge_.challenger = msg.sender;
challenge_.metadataURI = _metadataURI;
challenge_.metadataHash = _metadataHash;
challenge_.answer = Answer.PENDING;
challenge_.resolution = Resolution.PENDING;
emit Challenged(_entryID, _challengeID, msg.sender, _amount, _metadataURI, _metadataHash);
for(uint256 i = 0; i < entry_.vouchersAddress.length; i++) {
Voucher storage voucher_ = entry_.vouchers[entry_.vouchersAddress[i]];
if (voucher_.available > uint256(0)) {
uint256 _blocked = voucher_.available.mul(_fee).div(PCT_BASE);
voucher_.available = voucher_.available.sub(_blocked);
voucher_.blockedPerChallenge[_challengeID] = _blocked;
}
}
token_.safeTransferFrom(msg.sender, this, _amount);
}
/**
* @dev Accepts a challenge. Can only be called by the owner of the challenged entry.
*/
function accept(uint256 _challengeID) public existingChallenge(_challengeID) {
Challenge storage challenge_ = challenges_[_challengeID];
require(challenge_.answer == Answer.PENDING, "Given challenge was already answered");
require(_canAnswer(msg.sender, challenge_), "Challenges can only be answered by the entry owner during the answer period");
challenge_.answer = Answer.ACCEPTED;
challenge_.answeredAt = now;
emit Accepted(_challengeID);
}
/**
* @dev Rejects a challenge. Can only be called by the owner of the challenged entry.
*/
function reject(uint256 _challengeID) public existingChallenge(_challengeID) {
Challenge storage challenge_ = challenges_[_challengeID];
require(challenge_.answer == Answer.PENDING, "Given challenge was already answered");
require(_canAnswer(msg.sender, challenge_), "Challenges can only be answered by the entry owner during the answer period");
challenge_.answer = Answer.REJECTED;
challenge_.answeredAt = now;
emit Rejected(_challengeID);
}
/**
* @dev Appeals a decision by the vouched entry owner to accept or reject a decision. Any ZEP token holder can
* perform an appeal, staking a certain amount of tokens on it.
*/
function appeal(uint256 _challengeID) public existingChallenge(_challengeID) {
Challenge storage challenge_ = challenges_[_challengeID];
Appeal storage appeal_ = challenge_.appeal;
require(_withinAppealPeriod(challenge_), "The appeal period has ended");
require(appeal_.appealer == address(0), "Given challenge was already appealed");
require(challenge_.answer != Answer.PENDING, "Cannot appeal a not-answered challenge");
require(!_isOwner(msg.sender, challenge_.entryID), "The owner of a vouched entry can not appeal their own decision");
appeal_.appealer = msg.sender;
appeal_.createdAt = now;
appeal_.amount = challenge_.amount.mul(appealFee_).div(PCT_BASE);
emit Appealed(_challengeID, msg.sender, appeal_.amount);
token_.safeTransferFrom(msg.sender, this, appeal_.amount);
}
/**
* @dev Affirms an appeal on a challenge. Can only be called by the appeals resolver.
*/
function affirmAppeal(uint256 _challengeID) public onlyAppealsResolver existingChallenge(_challengeID) {
Challenge storage challenge_ = challenges_[_challengeID];
require(challenge_.resolution == Resolution.PENDING, "Given challenge was already resolved");
require(challenge_.appeal.appealer != address(0), "Cannot affirm a not-appealed challenge");
challenge_.resolution = Resolution.APPEAL_AFFIRMED;
emit AppealAffirmed(_challengeID, appealsResolver_);
if (challenge_.answer == Answer.ACCEPTED) _releaseBlockedAmounts(challenge_);
else _suppressBlockedAmountsAndPayChallenger(challenge_);
token_.safeTransfer(challenge_.appeal.appealer, challenge_.appeal.amount);
}
/**
* @dev Rejects an appeal on a challenge. Can only be called by the appeals resolver.
*/
function dismissAppeal(uint256 _challengeID) public onlyAppealsResolver existingChallenge(_challengeID) {
Challenge storage challenge_ = challenges_[_challengeID];
require(challenge_.resolution == Resolution.PENDING, "Given challenge was already resolved");
require(challenge_.appeal.appealer != address(0), "Cannot dismiss a not-appealed challenge");
challenge_.resolution = Resolution.APPEAL_DISMISSED;
emit AppealDismissed(_challengeID, appealsResolver_);
if (challenge_.answer == Answer.REJECTED) _releaseBlockedAmountsIncludingAppeal(challenge_);
else _suppressBlockedAmountsAndPayChallengerIncludingAppeal(challenge_);
}
/**
* @dev Confirms the result of a challenge if it has not been appealed and the challenge period has passed.
* Transfers tokens associated to the challenge as needed.
*/
function confirm(uint256 _challengeID) public existingChallenge(_challengeID) {
Challenge storage challenge_ = challenges_[_challengeID];
require(challenge_.answer != Answer.PENDING, "Cannot confirm a not-answered challenge");
require(challenge_.resolution == Resolution.PENDING, "Given challenge was already resolved");
require(challenge_.appeal.appealer == address(0), "Cannot confirm an appealed challenge");
require(!_withinAppealPeriod(challenge_), "Cannot confirm a challenge during the appeal period");
challenge_.resolution = Resolution.CONFIRMED;
emit Confirmed(_challengeID);
if (challenge_.answer == Answer.REJECTED) _releaseBlockedAmounts(challenge_);
else _suppressBlockedAmountsAndPayChallenger(challenge_);
}
function _existsEntry(uint256 _entryID) internal view returns (bool) {
return _entryID < entries_.length;
}
function _existsChallenge(uint256 _entryID) internal view returns (bool) {
return _entryID < challenges_.length;
}
function _isOwner(address _someone, uint256 _entryID) internal view returns (bool) {
return entries_[_entryID].owner == _someone;
}
function _vouched(uint256 _entryID, address _voucher) internal view returns (uint256) {
return entries_[_entryID].vouchers[_voucher].vouched;
}
function _available(uint256 _id, address _voucher) internal view returns (uint256) {
return entries_[_id].vouchers[_voucher].available;
}
function _canAnswer(address _someone, Challenge storage challenge_) internal view returns (bool) {
return _isOwner(_someone, challenge_.entryID) || !_withinAnswerPeriod(challenge_);
}
function _withinAnswerPeriod(Challenge storage challenge_) internal view returns (bool) {
return challenge_.createdAt.add(ANSWER_WINDOW) >= now;
}
function _withinAppealPeriod(Challenge storage challenge_) internal view returns (bool) {
return challenge_.answeredAt.add(APPEAL_WINDOW) >= now;
}
function _vouch(Entry storage entry_, address _voucher, uint256 _amount) internal {
require(entry_.vouchersAddress.length < MAX_VOUCHERS, "Given entry has reached the maximum amount of vouchers");
Voucher storage voucher_ = entry_.vouchers[_voucher];
if (voucher_.addr == address(0)) {
voucher_.addr = _voucher;
uint256 _voucherIndex = entry_.vouchersAddress.length;
entry_.vouchersAddress.push(_voucher);
entry_.vouchersAddressIndex[_voucher] = _voucherIndex;
}
voucher_.vouched = voucher_.vouched.add(_amount);
voucher_.available = voucher_.available.add(_amount);
emit Vouched(entry_.id, _voucher, _amount);
}
function _suppressBlockedAmountsAndPayChallenger(Challenge storage challenge_) internal {
_suppressBlockedAmounts(challenge_);
uint256 _payout = challenge_.amount.mul(2);
token_.safeTransfer(challenge_.challenger, _payout);
}
function _suppressBlockedAmountsAndPayChallengerIncludingAppeal(Challenge storage challenge_) internal {
_suppressBlockedAmounts(challenge_);
uint256 _payout = challenge_.amount.mul(2).add(challenge_.appeal.amount);
token_.safeTransfer(challenge_.challenger, _payout);
}
function _suppressBlockedAmounts(Challenge storage challenge_) internal {
Entry storage entry_ = entries_[challenge_.entryID];
entry_.totalVouched = entry_.totalVouched.sub(challenge_.amount);
for(uint256 i = 0; i < entry_.vouchersAddress.length; i++) {
Voucher storage voucher_ = entry_.vouchers[entry_.vouchersAddress[i]];
uint256 _blocked = voucher_.blockedPerChallenge[challenge_.id];
if (_blocked > uint256(0)) {
voucher_.vouched = voucher_.vouched.sub(_blocked);
voucher_.blockedPerChallenge[challenge_.id] = uint256(0);
}
}
}
function _releaseBlockedAmounts(Challenge storage challenge_) internal {
Entry storage entry_ = entries_[challenge_.entryID];
entry_.totalVouched = entry_.totalVouched.add(challenge_.amount);
entry_.totalAvailable = entry_.totalAvailable.add(challenge_.amount.mul(2));
for(uint256 i = 0; i < entry_.vouchersAddress.length; i++) {
Voucher storage voucher_ = entry_.vouchers[entry_.vouchersAddress[i]];
uint256 _blocked = voucher_.blockedPerChallenge[challenge_.id];
if (_blocked > uint256(0)) {
voucher_.vouched = voucher_.vouched.add(_blocked);
voucher_.available = voucher_.available.add(_blocked.mul(2));
voucher_.blockedPerChallenge[challenge_.id] = uint256(0);
}
}
}
function _releaseBlockedAmountsIncludingAppeal(Challenge storage challenge_) internal {
Entry storage entry_ = entries_[challenge_.entryID];
uint256 _appealAmount = challenge_.appeal.amount;
uint256 _totalProfit = challenge_.amount.add(_appealAmount);
entry_.totalVouched = entry_.totalVouched.add(_totalProfit);
entry_.totalAvailable = entry_.totalAvailable.add(_totalProfit).add(challenge_.amount);
for(uint256 i = 0; i < entry_.vouchersAddress.length; i++) {
Voucher storage voucher_ = entry_.vouchers[entry_.vouchersAddress[i]];
uint256 _blocked = voucher_.blockedPerChallenge[challenge_.id];
if (_blocked > uint256(0)) {
uint256 _appealProfit = _appealAmount.mul(_blocked).div(challenge_.amount);
uint256 _voucherProfit = _blocked.add(_appealProfit);
voucher_.vouched = voucher_.vouched.add(_voucherProfit);
voucher_.available = voucher_.available.add(_voucherProfit).add(_blocked);
voucher_.blockedPerChallenge[challenge_.id] = uint256(0);
}
}
}
function _removeVoucher(Entry storage entry_, address _voucher) private {
uint256 _voucherIndex = entry_.vouchersAddressIndex[_voucher];
uint256 _lastVoucherIndex = entry_.vouchersAddress.length.sub(1);
address _lastVoucher = entry_.vouchersAddress[_lastVoucherIndex];
entry_.vouchersAddress[_voucherIndex] = _lastVoucher;
entry_.vouchersAddress.length--;
entry_.vouchersAddressIndex[_voucher] = 0;
entry_.vouchersAddressIndex[_lastVoucher] = _voucherIndex;
}
}
|
Initializer function. Called only once when a proxy for the contract is created. _minimumStake uint256 that defines the minimum initial amount of vouched tokens a dependency can have when being created. _token ERC20 token to be used for vouching on dependencies./
|
function initialize(ERC20 _token, uint256 _minimumStake, uint256 _appealFee, address _appealsResolver) initializer public {
require(_token != address(0), "The token address cannot be zero");
require(_appealsResolver != address(0), "The appeals resolver address cannot be zero");
token_ = _token;
appealFee_ = _appealFee;
minimumStake_ = _minimumStake;
appealsResolver_ = _appealsResolver;
}
| 12,554,535 |
./full_match/80001/0x93606Db8e1340eBa115633Cc8a031D379D7638C6/sources/contracts/dev/vendor/openzeppelin-solidity/v.4.8.0/contracts/utils/SafeCast.sol
|
Returns the downcasted int144 from int256, reverting on overflow (when the input is less than smallest int144 or greater than largest int144). Counterpart to Solidity's `int144` operator. Requirements: - input must fit into 144 bits _Available since v4.7._/
|
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
| 5,640,084 |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
interface DharmaTradeReserveV15Interface {
event Trade(
address account,
address suppliedAsset,
address receivedAsset,
address retainedAsset,
uint256 suppliedAmount,
uint256 recievedAmount,
uint256 retainedAmount
);
event RoleModified(Role indexed role, address account);
event RolePaused(Role indexed role);
event RoleUnpaused(Role indexed role);
event EtherReceived(address sender, uint256 amount);
event GasReserveRefilled(uint256 etherAmount);
event Withdrawal(
string indexed asset, address indexed primaryRecipient, uint256 amount
);
enum Role { // #
DEPOSIT_MANAGER, // 0
ADJUSTER, // 1
WITHDRAWAL_MANAGER, // 2
RESERVE_TRADER, // 3
PAUSER, // 4
GAS_RESERVE_REFILLER // 5
}
enum TradeType {
DAI_TO_TOKEN,
DAI_TO_ETH,
ETH_TO_DAI,
TOKEN_TO_DAI,
ETH_TO_TOKEN,
TOKEN_TO_ETH,
TOKEN_TO_TOKEN
}
struct RoleStatus {
address account;
bool paused;
}
function tradeDaiForEtherV2(
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function tradeDDaiForEther(
uint256 daiEquivalentAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed);
function tradeEtherForDaiV2(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function tradeEtherForDaiAndMintDDai(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold);
function tradeDDaiForToken(
address token,
uint256 daiEquivalentAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed);
function tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought);
function tradeTokenForDaiAndMintDDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought);
function tradeEtherForToken(
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold);
function tradeEtherForTokenUsingEtherizer(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold);
function tradeTokenForToken(
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold);
function tradeTokenForTokenUsingReserves(
ERC20Interface tokenProvidedFromReserves,
address tokenReceived,
uint256 tokenProvidedAmountFromReserves,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold);
function tradeDaiForEtherUsingReservesV2(
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function tradeEtherForDaiUsingReservesAndMintDDaiV2(
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeDaiForTokenUsingReserves(
address token,
uint256 daiAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold);
function tradeTokenForDaiUsingReservesAndMintDDai(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function tradeTokenForEtherUsingReserves(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought);
function tradeEtherForTokenUsingReserves(
address token,
uint256 etherAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold);
function finalizeEtherDeposit(
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external;
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external;
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external;
function mint(uint256 daiAmount) external returns (uint256 dDaiMinted);
function redeem(uint256 dDaiAmount) external returns (uint256 daiReceived);
function redeemUnderlying(
uint256 daiAmount
) external returns (uint256 dDaiSupplied);
function tradeDDaiForUSDC(
uint256 daiEquivalentAmount, uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function tradeUSDCForDDai(
uint256 usdcAmount, uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function refillGasReserve(uint256 etherAmount) external;
function withdrawUSDC(address recipient, uint256 usdcAmount) external;
function withdrawDai(address recipient, uint256 daiAmount) external;
function withdrawDharmaDai(address recipient, uint256 dDaiAmount) external;
function withdrawUSDCToPrimaryRecipient(uint256 usdcAmount) external;
function withdrawDaiToPrimaryRecipient(uint256 usdcAmount) external;
function withdrawEtherToPrimaryRecipient(uint256 etherAmount) external;
function withdrawEther(
address payable recipient, uint256 etherAmount
) external;
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external returns (bool success);
function callAny(
address payable target, uint256 amount, bytes calldata data
) external returns (bool ok, bytes memory returnData);
function setDaiLimit(uint256 daiAmount) external;
function setEtherLimit(uint256 daiAmount) external;
function setPrimaryUSDCRecipient(address recipient) external;
function setPrimaryDaiRecipient(address recipient) external;
function setPrimaryEtherRecipient(address recipient) external;
function setRole(Role role, address account) external;
function removeRole(Role role) external;
function pause(Role role) external;
function unpause(Role role) external;
function isPaused(Role role) external view returns (bool paused);
function isRole(Role role) external view returns (bool hasRole);
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet);
function getDepositManager() external view returns (address depositManager);
function getAdjuster() external view returns (address adjuster);
function getReserveTrader() external view returns (address reserveTrader);
function getWithdrawalManager() external view returns (
address withdrawalManager
);
function getPauser() external view returns (address pauser);
function getGasReserveRefiller() external view returns (
address gasReserveRefiller
);
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
);
function getDaiLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
);
function getEtherLimit() external view returns (uint256 etherAmount);
function getPrimaryUSDCRecipient() external view returns (
address recipient
);
function getPrimaryDaiRecipient() external view returns (
address recipient
);
function getPrimaryEtherRecipient() external view returns (
address recipient
);
function getImplementation() external view returns (address implementation);
function getInstance() external pure returns (address instance);
function getVersion() external view returns (uint256 version);
}
interface ERC20Interface {
function balanceOf(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function allowance(address, address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
interface DTokenInterface {
function redeem(
uint256 dTokensToBurn
) external returns (uint256 underlyingReceived);
function balanceOf(address) external view returns (uint256);
function balanceOfUnderlying(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function exchangeRateCurrent() external view returns (uint256);
}
interface DharmaDaiExchangerInterface {
function mintTo(
address account, uint256 daiToSupply
) external returns (uint256 dDaiMinted);
function redeemUnderlyingTo(
address account, uint256 daiToReceive
) external returns (uint256 dDaiBurned);
}
interface TradeHelperInterface {
function tradeUSDCForDDai(
uint256 amountUSDC,
uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function tradeDDaiForUSDC(
uint256 amountDai,
uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function getExpectedDai(uint256 usdc) external view returns (uint256 dai);
function getExpectedUSDC(uint256 dai) external view returns (uint256 usdc);
}
interface UniswapV2Interface {
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface EtherReceiverInterface {
function settleEther() external;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*
* In order to transfer ownership, a recipient must be specified, at which point
* the specified recipient can call `acceptOwnership` and take ownership.
*/
contract TwoStepOwnable {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
/**
* @dev Allows a new account (`newOwner`) to accept ownership.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
/**
* @dev Cancel a transfer of ownership to a new account.
* Can only be called by the current owner.
*/
function cancelOwnershipTransfer() external onlyOwner {
delete _newPotentialOwner;
}
/**
* @dev Transfers ownership of the contract to the caller.
* Can only be called by a new potential owner set by the current owner.
*/
function acceptOwnership() external {
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OwnershipTransferred(_owner, msg.sender);
_owner = msg.sender;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() external view returns (address) {
return _owner;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
/**
* @title DharmaTradeReserveV15ImplementationStaging
* @author 0age
* @notice This contract manages Dharma's reserves. It designates a collection
* of "roles" - these are dedicated accounts that can be modified by the owner,
* and that can trigger specific functionality on the reserve. These roles are:
* - depositManager (0): initiates Eth / token transfers to smart wallets
* - adjuster (1): mints / redeems Dai, and swaps USDC, for dDai
* - withdrawalManager (2): initiates transfers to recipients set by the owner
* - reserveTrader (3): initiates trades using funds held in reserve
* - pauser (4): pauses any role (only the owner is then able to unpause it)
* - gasReserveRefiller (5): transfers Ether to the Dharma Gas Reserve
*
* When finalizing deposits, the deposit manager must adhere to two constraints:
* - it must provide "proof" that the recipient is a smart wallet by including
* the initial user signing key used to derive the smart wallet address
* - it must not attempt to transfer more Eth, Dai, or the Dai-equivalent
* value of Dharma Dai, than the current "limit" set by the owner.
*
* Note that "proofs" can be validated via `isSmartWallet`.
*/
contract DharmaTradeReserveV15ImplementationStaging is DharmaTradeReserveV15Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a "primary recipient" the withdrawal manager can transfer Dai to.
address private _primaryDaiRecipient;
// Maintain a "primary recipient" the withdrawal manager can transfer USDC to.
address private _primaryUSDCRecipient;
// Maintain a maximum allowable Dai transfer size for the deposit manager.
uint256 private _daiLimit;
// Maintain a maximum allowable Ether transfer size for the deposit manager.
uint256 private _etherLimit;
bool private _unused; // unused, don't change storage layout
// Maintain a "primary recipient" where withdrawal manager can transfer Ether.
address private _primaryEtherRecipient;
uint256 private constant _VERSION = 1015;
// This contract interacts with USDC, Dai, and Dharma Dai.
ERC20Interface internal constant _USDC = ERC20Interface(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ERC20Interface internal constant _DAI = ERC20Interface(
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _ETHERIZER = ERC20Interface(
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
DTokenInterface internal constant _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430
);
DharmaDaiExchangerInterface internal constant _DDAI_EXCHANGER = (
DharmaDaiExchangerInterface(
0x83E02F0b169be417C38d1216fc2a5134C48Af44a
)
);
TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface(
0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d
);
UniswapV2Interface internal constant _UNISWAP_ROUTER = UniswapV2Interface(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
EtherReceiverInterface internal constant _ETH_RECEIVER = (
EtherReceiverInterface(
0xaf84687D21736F5E06f738c6F065e88890465E7c
)
);
address internal constant _WETH = address(
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
);
address internal constant _GAS_RESERVE = address(
0x09cd826D4ABA4088E1381A1957962C946520952d // staging version
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _CREATE2_HEADER = bytes21(
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000";
bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28(
0x00000000000000000000000000000000000000000000000000000000
);
string internal constant _TRANSFER_SIZE_EXCEEDED = string(
"Transfer size exceeds limit."
);
function initialize() external onlyOwner {
require(_DAI.approve(address(_DDAI_EXCHANGER), uint256(-1)));
require(_DDAI.approve(address(_DDAI_EXCHANGER), uint256(-1)));
}
// Include a payable fallback so that the contract can receive Ether payments.
function () external payable {
emit EtherReceived(msg.sender, msg.value);
}
/**
* @notice Pull in `daiAmount` Dai from the caller, trade it for Ether using
* UniswapV2, and return `quotedEtherAmount` Ether to the caller.
* @param daiAmount uint256 The Dai amount to supply when trading for Ether.
* @param quotedEtherAmount uint256 The amount of Ether to return to caller.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai sold as part of the trade.
*/
function tradeDaiForEtherV2(
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_transferInToken(_DAI, msg.sender, daiAmount);
// Trade Dai for Ether.
totalDaiSold = _tradeDaiForEther(
daiAmount, quotedEtherAmount, deadline, false
);
}
function tradeDDaiForEther(
uint256 daiEquivalentAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed) {
// Transfer in sufficient dDai and use it to mint Dai.
totalDDaiRedeemed = _transferAndRedeemDDai(daiEquivalentAmount);
// Trade minted Dai for Ether.
totalDaiSold = _tradeDaiForEther(
daiEquivalentAmount, quotedEtherAmount, deadline, false
);
}
function tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalEtherBought) {
// Transfer the tokens from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade tokens for Ether.
totalEtherBought = _tradeTokenForEther(
token, tokenAmount, quotedEtherAmount, deadline, false
);
// Transfer the quoted Ether amount to the caller.
_transferEther(msg.sender, quotedEtherAmount);
}
function tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_transferInToken(_DAI, msg.sender, daiAmount);
// Trade Dai for specified token.
totalDaiSold = _tradeDaiForToken(
token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false
);
}
function tradeDDaiForToken(
address token,
uint256 daiEquivalentAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed) {
// Transfer in sufficient dDai and use it to mint Dai.
totalDDaiRedeemed = _transferAndRedeemDDai(daiEquivalentAmount);
// Trade minted Dai for specified token.
totalDaiSold = _tradeDaiForToken(
token,
daiEquivalentAmount,
quotedTokenAmount,
deadline,
routeThroughEther,
false
);
}
/**
* @notice Using `daiAmountFromReserves` Dai (note that dDai will be redeemed
* if necessary), trade for Ether using UniswapV2. Only the owner or the trade
* reserve role can call this function. Note that Dharma Dai will be redeemed
* to cover the Dai if there is not enough currently in the contract.
* @param daiAmountFromReserves the amount of Dai to take from reserves.
* @param quotedEtherAmount uint256 The Ether amount requested in the trade.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Ether bought as part of the trade.
*/
function tradeDaiForEtherUsingReservesV2(
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
_redeemDDaiIfNecessary(daiAmountFromReserves);
// Trade Dai for Ether using reserves.
totalDaiSold = _tradeDaiForEther(
daiAmountFromReserves, quotedEtherAmount, deadline, true
);
}
function tradeTokenForEtherUsingReserves(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedEtherAmount,
uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalEtherBought
) {
// Trade tokens for Ether using reserves.
totalEtherBought = _tradeTokenForEther(
token, tokenAmountFromReserves, quotedEtherAmount, deadline, true
);
}
/**
* @notice Accept `msg.value` Ether from the caller, trade it for Dai using
* UniswapV2, and return `quotedDaiAmount` Dai to the caller.
* @param quotedDaiAmount uint256 The amount of Dai to return to the caller.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai bought as part of the trade.
*/
function tradeEtherForDaiV2(
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Trade Ether for Dai.
totalDaiBought = _tradeEtherForDai(
msg.value, quotedDaiAmount, deadline, false
);
// Transfer the Dai to the caller and revert on failure.
_transferToken(_DAI, msg.sender, quotedDaiAmount);
}
function tradeEtherForDaiAndMintDDai(
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought, uint256 totalDDaiMinted) {
// Trade Ether for Dai.
totalDaiBought = _tradeEtherForDai(
msg.value, quotedDaiAmount, deadline, false
);
// Mint dDai to caller using quoted amount (retained amount stays in Dai).
totalDDaiMinted = _mintDDai(quotedDaiAmount, true);
}
function tradeEtherForToken(
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold) {
// Trade Ether for the specified token.
totalEtherSold = _tradeEtherForToken(
token, msg.value, quotedTokenAmount, deadline, false
);
}
function tradeEtherForTokenUsingEtherizer(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline
) external returns (uint256 totalEtherSold) {
// Transfer the Ether from the caller and revert on failure.
_transferInToken(_ETHERIZER, msg.sender, etherAmount);
// Trade Ether for the specified token.
totalEtherSold = _tradeEtherForToken(
token, etherAmount, quotedTokenAmount, deadline, false
);
}
function tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought) {
// Transfer the token from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade the token for Dai.
totalDaiBought = _tradeTokenForDai(
token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false
);
// Transfer the quoted Dai amount to the caller and revert on failure.
_transferToken(_DAI, msg.sender, quotedDaiAmount);
}
function tradeTokenForDaiAndMintDDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted) {
// Transfer the token from the caller and revert on failure.
_transferInToken(token, msg.sender, tokenAmount);
// Trade the token for Dai.
totalDaiBought = _tradeTokenForDai(
token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false
);
// Mint dDai to caller using quoted amount (retained amount stays in Dai).
totalDDaiMinted = _mintDDai(quotedDaiAmount, true);
}
function tradeTokenForToken(
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external returns (uint256 totalTokensSold) {
// Transfer the token from the caller and revert on failure.
_transferInToken(tokenProvided, msg.sender, tokenProvidedAmount);
totalTokensSold = _tradeTokenForToken(
msg.sender,
tokenProvided,
tokenReceived,
tokenProvidedAmount,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
);
}
function tradeTokenForTokenUsingReserves(
ERC20Interface tokenProvidedFromReserves,
address tokenReceived,
uint256 tokenProvidedAmountFromReserves,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalTokensSold
) {
totalTokensSold = _tradeTokenForToken(
address(this),
tokenProvidedFromReserves,
tokenReceived,
tokenProvidedAmountFromReserves,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
);
}
/**
* @notice Using `etherAmountFromReserves`, trade for Dai using UniswapV2,
* and use that Dai to mint Dharma Dai.
* Only the owner or the trade reserve role can call this function.
* @param etherAmountFromReserves the amount of Ether to take from reserves
* and add to the provided amount.
* @param quotedDaiAmount uint256 The amount of Dai requested in the trade.
* @param deadline uint256 The timestamp the order is valid until.
* @return The amount of Dai bought as part of the trade.
*/
function tradeEtherForDaiUsingReservesAndMintDDaiV2(
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade Ether for Dai using reserves.
totalDaiBought = _tradeEtherForDai(
etherAmountFromReserves, quotedDaiAmount, deadline, true
);
// Mint dDai using the received Dai.
totalDDaiMinted = _mintDDai(totalDaiBought, false);
}
function tradeEtherForTokenUsingReserves(
address token,
uint256 etherAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) {
// Trade Ether for token using reserves.
totalEtherSold = _tradeEtherForToken(
token, etherAmountFromReserves, quotedTokenAmount, deadline, true
);
}
function tradeDaiForTokenUsingReserves(
address token,
uint256 daiAmountFromReserves,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
_redeemDDaiIfNecessary(daiAmountFromReserves);
// Trade Dai for token using reserves.
totalDaiSold = _tradeDaiForToken(
token,
daiAmountFromReserves,
quotedTokenAmount,
deadline,
routeThroughEther,
true
);
}
function tradeTokenForDaiUsingReservesAndMintDDai(
ERC20Interface token,
uint256 tokenAmountFromReserves,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther
) external onlyOwnerOr(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade the token for Dai using reserves.
totalDaiBought = _tradeTokenForDai(
token,
tokenAmountFromReserves,
quotedDaiAmount,
deadline,
routeThroughEther,
true
);
// Mint dDai using the received Dai.
totalDDaiMinted = _mintDDai(totalDaiBought, false);
}
/**
* @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial
* user signing key `initialUserSigningKey` as proof that the specified smart
* wallet is indeed a Dharma Smart Wallet - this assumes that the address is
* derived and deployed using the Dharma Smart Wallet Factory V1. In addition,
* the specified amount must be less than the configured limit amount. Only
* the owner or the designated deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param daiAmount uint256 The amount of Dai to transfer - this must be less
* than the current limit.
*/
function finalizeDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _daiLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the Dai to the specified smart wallet.
_transferToken(_DAI, smartWallet, daiAmount);
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Dai equivalent value of the specified dDai amount must
* be less than the configured limit amount. Only the owner or the designated
* deposit manager role may call this function.
* @param smartWallet address The smart wallet to transfer Dai to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai
* equivalent amount must be less than the current limit.
*/
function finalizeDharmaDaiDeposit(
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Get the current dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Invalid dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _daiLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the dDai to the specified smart wallet.
_transferToken(ERC20Interface(address(_DDAI)), smartWallet, dDaiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to `smartWallet`, providing the
* initial user signing key `initialUserSigningKey` as proof that the
* specified smart wallet is indeed a Dharma Smart Wallet - this assumes that
* the address is derived and deployed using the Dharma Smart Wallet Factory
* V1. In addition, the Ether amount must be less than the configured limit
* amount. Only the owner or the designated deposit manager role may call this
* function.
* @param smartWallet address The smart wallet to transfer Ether to.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @param etherAmount uint256 The amount of Ether to transfer - this amount
* must be less than the current limit.
*/
function finalizeEtherDeposit(
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external onlyOwnerOr(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ensureSmartWallet(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(etherAmount < _etherLimit, _TRANSFER_SIZE_EXCEEDED);
// Transfer the Ether to the specified smart wallet.
_transferEther(smartWallet, etherAmount);
}
/**
* @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to supply when minting Dharma
* Dai.
* @return The amount of Dharma Dai minted.
*/
function mint(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _mintDDai(daiAmount, false);
}
/**
* @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the
* designated adjuster role may call this function.
* @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming
* for Dai.
* @return The amount of Dai received.
*/
function redeem(
uint256 dDaiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) {
// Redeem the specified amount of dDai for Dai.
daiReceived = _DDAI.redeem(dDaiAmount);
}
/**
* @notice Receive `daiAmount` Dai in exchange for Dharma Dai. Only the owner
* or the designated adjuster role may call this function.
* @param daiAmount uint256 The amount of Dai to receive when redeeming
* Dharma Dai.
* @return The amount of Dharma Dai supplied.
*/
function redeemUnderlying(
uint256 daiAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiSupplied) {
// Redeem the specified amount of dDai for Dai.
dDaiSupplied = _DDAI_EXCHANGER.redeemUnderlyingTo(address(this), daiAmount);
}
/**
* @notice trade `usdcAmount` USDC for Dharma Dai. Only the owner or the
* designated adjuster role may call this function.
* @param usdcAmount uint256 The amount of USDC to supply when trading for
* Dharma Dai.
* @param quotedDaiEquivalentAmount uint256 The expected DAI equivalent value
* of the received dDai - this value is returned from the `getAndExpectedDai`
* view function on the trade helper.
* @return The amount of dDai received.
*/
function tradeUSDCForDDai(
uint256 usdcAmount,
uint256 quotedDaiEquivalentAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) {
dDaiMinted = _TRADE_HELPER.tradeUSDCForDDai(
usdcAmount, quotedDaiEquivalentAmount
);
}
/**
* @notice tradeDDaiForUSDC `daiEquivalentAmount` Dai amount to trade in
* Dharma Dai for USDC. Only the owner or the designated adjuster role may
* call this function.
* @param daiEquivalentAmount uint256 The Dai equivalent amount to supply in
* Dharma Dai when trading for USDC.
* @param quotedUSDCAmount uint256 The expected USDC received in exchange for
* dDai - this value is returned from the `getExpectedUSDC` view function on
* the trade helper.
* @return The amount of USDC received.
*/
function tradeDDaiForUSDC(
uint256 daiEquivalentAmount,
uint256 quotedUSDCAmount
) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 usdcReceived) {
usdcReceived = _TRADE_HELPER.tradeDDaiForUSDC(
daiEquivalentAmount, quotedUSDCAmount
);
}
function refillGasReserve(
uint256 etherAmount
) external onlyOwnerOr(Role.GAS_RESERVE_REFILLER) {
// Transfer the Ether to the gas reserve.
_transferEther(_GAS_RESERVE, etherAmount);
emit GasReserveRefilled(etherAmount);
}
/**
* @notice Transfer `usdcAmount` USDC to the current primary recipient set by
* the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param usdcAmount uint256 The amount of USDC to transfer to the primary
* recipient.
*/
function withdrawUSDCToPrimaryRecipient(
uint256 usdcAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryUSDCRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "USDC", usdcAmount
);
// Transfer the supplied USDC amount to the primary recipient.
_transferToken(_USDC, primaryRecipient, usdcAmount);
}
/**
* @notice Transfer `daiAmount` Dai to the current primary recipient set by
* the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param daiAmount uint256 The amount of Dai to transfer to the primary
* recipient.
*/
function withdrawDaiToPrimaryRecipient(
uint256 daiAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryDaiRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "Dai", daiAmount
);
// Transfer the supplied Dai amount to the primary recipient.
_transferToken(_DAI, primaryRecipient, daiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to the current primary recipient set
* by the owner. Only the owner or the designated withdrawal manager role may
* call this function.
* @param etherAmount uint256 The amount of Ether to transfer to the primary
* recipient.
*/
function withdrawEtherToPrimaryRecipient(
uint256 etherAmount
) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryEtherRecipient;
_ensurePrimaryRecipientIsSetAndEmitEvent(
primaryRecipient, "Ether", etherAmount
);
// Transfer the supplied Ether amount to the primary recipient.
_transferEther(primaryRecipient, etherAmount);
}
/**
* @notice Transfer `usdcAmount` USDC to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer USDC to.
* @param usdcAmount uint256 The amount of USDC to transfer.
*/
function withdrawUSDC(
address recipient, uint256 usdcAmount
) external onlyOwner {
// Transfer the USDC to the specified recipient.
_transferToken(_USDC, recipient, usdcAmount);
}
/**
* @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call
* this function.
* @param recipient address The account to transfer Dai to.
* @param daiAmount uint256 The amount of Dai to transfer.
*/
function withdrawDai(
address recipient, uint256 daiAmount
) external onlyOwner {
// Transfer the Dai to the specified recipient.
_transferToken(_DAI, recipient, daiAmount);
}
/**
* @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Dharma Dai to.
* @param dDaiAmount uint256 The amount of Dharma Dai to transfer.
*/
function withdrawDharmaDai(
address recipient, uint256 dDaiAmount
) external onlyOwner {
// Transfer the dDai to the specified recipient.
_transferToken(ERC20Interface(address(_DDAI)), recipient, dDaiAmount);
}
/**
* @notice Transfer `etherAmount` Ether to `recipient`. Only the owner may
* call this function.
* @param recipient address The account to transfer Ether to.
* @param etherAmount uint256 The amount of Ether to transfer.
*/
function withdrawEther(
address payable recipient, uint256 etherAmount
) external onlyOwner {
// Transfer the Ether to the specified recipient.
_transferEther(recipient, etherAmount);
}
/**
* @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the
* owner may call this function.
* @param token ERC20Interface The ERC20 token to transfer.
* @param recipient address The account to transfer the tokens to.
* @param amount uint256 The amount of tokens to transfer.
* @return A boolean to indicate if the transfer was successful - note that
* unsuccessful ERC20 transfers will usually revert.
*/
function withdraw(
ERC20Interface token, address recipient, uint256 amount
) external onlyOwner returns (bool success) {
// Transfer the token to the specified recipient.
success = token.transfer(recipient, amount);
}
/**
* @notice Call account `target`, supplying value `amount` and data `data`.
* Only the owner may call this function.
* @param target address The account to call.
* @param amount uint256 The amount of ether to include as an endowment.
* @param data bytes The data to include along with the call.
* @return A boolean to indicate if the call was successful, as well as the
* returned data or revert reason.
*/
function callAny(
address payable target, uint256 amount, bytes calldata data
) external onlyOwner returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
/**
* @notice Set `daiAmount` as the new limit on size of finalized deposits.
* Only the owner may call this function.
* @param daiAmount uint256 The new limit on the size of finalized deposits.
*/
function setDaiLimit(uint256 daiAmount) external onlyOwner {
// Set the new limit.
_daiLimit = daiAmount;
}
/**
* @notice Set `etherAmount` as the new limit on size of finalized deposits.
* Only the owner may call this function.
* @param etherAmount uint256 The new limit on the size of finalized deposits.
*/
function setEtherLimit(uint256 etherAmount) external onlyOwner {
// Set the new limit.
_etherLimit = etherAmount;
}
/**
* @notice Set `recipient` as the new primary recipient for USDC withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryUSDCRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryUSDCRecipient = recipient;
}
/**
* @notice Set `recipient` as the new primary recipient for Dai withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryDaiRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryDaiRecipient = recipient;
}
/**
* @notice Set `recipient` as the new primary recipient for Ether withdrawals.
* Only the owner may call this function.
* @param recipient address The new primary recipient.
*/
function setPrimaryEtherRecipient(address recipient) external onlyOwner {
// Set the new primary recipient.
_primaryEtherRecipient = recipient;
}
/**
* @notice Pause a currently unpaused role and emit a `RolePaused` event. Only
* the owner or the designated pauser may call this function. Also, bear in
* mind that only the owner may unpause a role once paused.
* @param role The role to pause.
*/
function pause(Role role) external onlyOwnerOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
/**
* @notice Unpause a currently paused role and emit a `RoleUnpaused` event.
* Only the owner may call this function.
* @param role The role to pause.
*/
function unpause(Role role) external onlyOwner {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role is already unpaused.");
storedRoleStatus.paused = false;
emit RoleUnpaused(role);
}
/**
* @notice Set a new account on a given role and emit a `RoleModified` event
* if the role holder has changed. Only the owner may call this function.
* @param role The role that the account will be set for.
* @param account The account to set as the designated role bearer.
*/
function setRole(Role role, address account) external onlyOwner {
require(account != address(0), "Must supply an account.");
_setRole(role, account);
}
/**
* @notice Remove any current role bearer for a given role and emit a
* `RoleModified` event if a role holder was previously set. Only the owner
* may call this function.
* @param role The role that the account will be removed from.
*/
function removeRole(Role role) external onlyOwner {
_setRole(role, address(0));
}
/**
* @notice External view function to check whether or not the functionality
* associated with a given role is currently paused or not. The owner or the
* pauser may pause any given role (including the pauser itself), but only the
* owner may unpause functionality. Additionally, the owner may call paused
* functions directly.
* @param role The role to check the pause status on.
* @return A boolean to indicate if the functionality associated with the role
* in question is currently paused.
*/
function isPaused(Role role) external view returns (bool paused) {
paused = _isPaused(role);
}
/**
* @notice External view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return A boolean indicating if the caller has the specified role.
*/
function isRole(Role role) external view returns (bool hasRole) {
hasRole = _isRole(role);
}
/**
* @notice External view function to check whether a "proof" that a given
* smart wallet is actually a Dharma Smart Wallet, based on the initial user
* signing key, is valid or not. This proof only works when the Dharma Smart
* Wallet in question is derived using V1 of the Dharma Smart Wallet Factory.
* @param smartWallet address The smart wallet to check.
* @param initialUserSigningKey address The initial user signing key supplied
* when deriving the smart wallet address - this could be an EOA or a Dharma
* key ring address.
* @return A boolean indicating if the specified smart wallet account is
* indeed a smart wallet based on the specified initial user signing key.
*/
function isDharmaSmartWallet(
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey);
}
/**
* @notice External view function to check the account currently holding the
* deposit manager role. The deposit manager can process standard deposit
* finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but
* must prove that the recipient is a Dharma Smart Wallet and adhere to the
* current deposit size limit.
* @return The address of the current deposit manager, or the null address if
* none is set.
*/
function getDepositManager() external view returns (address depositManager) {
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and
* vice-versa via minting or redeeming.
* @return The address of the current adjuster, or the null address if none is
* set.
*/
function getAdjuster() external view returns (address adjuster) {
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
/**
* @notice External view function to check the account currently holding the
* reserve trader role. The reserve trader can trigger trades that utilize
* reserves in addition to supplied funds, if any.
* @return The address of the current reserve trader, or the null address if
* none is set.
*/
function getReserveTrader() external view returns (address reserveTrader) {
reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account;
}
/**
* @notice External view function to check the account currently holding the
* withdrawal manager role. The withdrawal manager can transfer USDC, Dai, and
* Ether to their respective "primary recipient" accounts set by the owner.
* @return The address of the current withdrawal manager, or the null address
* if none is set.
*/
function getWithdrawalManager() external view returns (
address withdrawalManager
) {
withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account;
}
/**
* @notice External view function to check the account currently holding the
* pauser role. The pauser can pause any role from taking its standard action,
* though the owner will still be able to call the associated function in the
* interim and is the only entity able to unpause the given role once paused.
* @return The address of the current pauser, or the null address if none is
* set.
*/
function getPauser() external view returns (address pauser) {
pauser = _roles[uint256(Role.PAUSER)].account;
}
function getGasReserveRefiller() external view returns (
address gasReserveRefiller
) {
gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account;
}
/**
* @notice External view function to check the current reserves held by this
* contract.
* @return The Dai and Dharma Dai reserves held by this contract, as well as
* the Dai-equivalent value of the Dharma Dai reserves.
*/
function getReserves() external view returns (
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _DAI.balanceOf(address(this));
dDai = _DDAI.balanceOf(address(this));
dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this));
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing deposits, expressed in Dai
* and in Dharma Dai.
* @return The Dai and Dharma Dai limit on deposit finalization amount.
*/
function getDaiLimit() external view returns (
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _daiLimit;
dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent());
}
/**
* @notice External view function to check the current limit on deposit amount
* enforced for the deposit manager when finalizing Ether deposits.
* @return The Ether limit on deposit finalization amount.
*/
function getEtherLimit() external view returns (uint256 etherAmount) {
etherAmount = _etherLimit;
}
/**
* @notice External view function to check the address of the current
* primary recipient for USDC.
* @return The primary recipient for USDC.
*/
function getPrimaryUSDCRecipient() external view returns (
address recipient
) {
recipient = _primaryUSDCRecipient;
}
/**
* @notice External view function to check the address of the current
* primary recipient for Dai.
* @return The primary recipient for Dai.
*/
function getPrimaryDaiRecipient() external view returns (
address recipient
) {
recipient = _primaryDaiRecipient;
}
/**
* @notice External view function to check the address of the current
* primary recipient for Ether.
* @return The primary recipient for Ether.
*/
function getPrimaryEtherRecipient() external view returns (
address recipient
) {
recipient = _primaryEtherRecipient;
}
/**
* @notice External view function to check the current implementation
* of this contract (i.e. the "logic" for the contract).
* @return The current implementation for this contract.
*/
function getImplementation() external view returns (
address implementation
) {
(bool ok, bytes memory returnData) = address(
0x481B1a16E6675D33f8BBb3a6A58F5a9678649718
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
/**
* @notice External pure function to get the address of the actual
* contract instance (i.e. the "storage" foor this contract).
* @return The address of this contract instance.
*/
function getInstance() external pure returns (address instance) {
instance = address(0x2040F2f2bB228927235Dc24C33e99E3A0a7922c1);
}
function getVersion() external view returns (uint256 version) {
version = _VERSION;
}
function _grantUniswapRouterApprovalIfNecessary(
ERC20Interface token, uint256 amount
) internal {
if (token.allowance(address(this), address(_UNISWAP_ROUTER)) < amount) {
// Try removing router approval first as a workaround for unusual tokens.
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), uint256(0)
)
);
// Approve Uniswap router to transfer tokens on behalf of this contract.
(success, data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), uint256(-1)
)
);
if (!success) {
// Some janky tokens only allow setting approval up to current balance.
(success, data) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, address(_UNISWAP_ROUTER), amount
)
);
}
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Uniswap router token approval failed."
);
}
}
function _tradeEtherForDai(
uint256 etherAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalDaiBought) {
// Establish path from Ether to Dai.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
_WETH, address(_DAI), false
);
// Trade Ether for Dai on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactETHForTokens.value(etherAmount)(
quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
_fireTradeEvent(
fromReserves,
TradeType.ETH_TO_DAI,
address(0),
etherAmount,
quotedDaiAmount,
totalDaiBought.sub(quotedDaiAmount)
);
}
function _tradeDaiForEther(
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalDaiSold) {
// Establish path from Dai to Ether.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(_DAI), _WETH, false
);
// Trade Dai for quoted Ether amount on Uniswap (send to correct recipient).
amounts = _UNISWAP_ROUTER.swapTokensForExactETH(
quotedEtherAmount,
daiAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalDaiSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.DAI_TO_ETH,
address(0),
daiAmount,
quotedEtherAmount,
daiAmount.sub(totalDaiSold)
);
}
function _tradeEtherForToken(
address token,
uint256 etherAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalEtherSold) {
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
_WETH, address(token), false
);
// Trade Ether for the quoted token amount and send to correct recipient.
amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)(
quotedTokenAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalEtherSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.ETH_TO_TOKEN,
address(token),
etherAmount,
quotedTokenAmount,
etherAmount.sub(totalEtherSold)
);
}
function _tradeTokenForEther(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedEtherAmount,
uint256 deadline,
bool fromReserves
) internal returns (uint256 totalEtherBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(token, tokenAmount);
// Establish path from target token to Ether.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(token), _WETH, false
);
// Trade tokens for quoted Ether amount on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForETH(
tokenAmount, quotedEtherAmount, path, address(this), deadline
);
totalEtherBought = amounts[1];
_fireTradeEvent(
fromReserves,
TradeType.TOKEN_TO_ETH,
address(token),
tokenAmount,
quotedEtherAmount,
totalEtherBought.sub(quotedEtherAmount)
);
}
function _tradeDaiForToken(
address token,
uint256 daiAmount,
uint256 quotedTokenAmount,
uint256 deadline,
bool routeThroughEther,
bool fromReserves
) internal returns (uint256 totalDaiSold) {
// Establish path (direct or routed through Ether) from Dai to target token.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(_DAI), address(token), routeThroughEther
);
// Trade Dai for quoted token amount and send to correct recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenAmount,
daiAmount,
path,
fromReserves ? address(this) : msg.sender,
deadline
);
totalDaiSold = amounts[0];
_fireTradeEvent(
fromReserves,
TradeType.DAI_TO_TOKEN,
address(token),
daiAmount,
quotedTokenAmount,
daiAmount.sub(totalDaiSold)
);
}
function _tradeTokenForDai(
ERC20Interface token,
uint256 tokenAmount,
uint256 quotedDaiAmount,
uint256 deadline,
bool routeThroughEther,
bool fromReserves
) internal returns (uint256 totalDaiBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(token, tokenAmount);
// Establish path (direct or routed through Ether) from target token to Dai.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(token), address(_DAI), routeThroughEther
);
// Trade Dai for the quoted token amount on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForTokens(
tokenAmount, quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[path.length - 1];
_fireTradeEvent(
fromReserves,
TradeType.TOKEN_TO_DAI,
address(token),
tokenAmount,
quotedDaiAmount,
totalDaiBought.sub(quotedDaiAmount)
);
}
function _tradeTokenForToken(
address recipient,
ERC20Interface tokenProvided,
address tokenReceived,
uint256 tokenProvidedAmount,
uint256 quotedTokenReceivedAmount,
uint256 deadline,
bool routeThroughEther
) internal returns (uint256 totalTokensSold) {
uint256 retainedAmount;
// Approve Uniswap router to transfer tokens on behalf of this contract.
_grantUniswapRouterApprovalIfNecessary(tokenProvided, tokenProvidedAmount);
if (routeThroughEther == false) {
// Establish direct path between tokens.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), tokenReceived, false
);
// Trade for the quoted token amount on Uniswap and send to recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenReceivedAmount,
tokenProvidedAmount,
path,
recipient,
deadline
);
totalTokensSold = amounts[0];
retainedAmount = tokenProvidedAmount.sub(totalTokensSold);
} else {
// Establish path between provided token and WETH.
(address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), _WETH, false
);
// Trade all provided tokens for WETH on Uniswap (send to this contract).
amounts = _UNISWAP_ROUTER.swapExactTokensForTokens(
tokenProvidedAmount, 0, path, address(this), deadline
);
retainedAmount = amounts[1];
// Establish path between WETH and received token.
(path, amounts) = _createPathAndAmounts(
_WETH, tokenReceived, false
);
// Trade bought WETH for received token on Uniswap and send to recipient.
amounts = _UNISWAP_ROUTER.swapTokensForExactTokens(
quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline
);
totalTokensSold = amounts[0];
retainedAmount = retainedAmount.sub(totalTokensSold);
}
emit Trade(
recipient,
address(tokenProvided),
tokenReceived,
routeThroughEther ? _WETH : address(tokenProvided),
tokenProvidedAmount,
quotedTokenReceivedAmount,
retainedAmount
);
}
/**
* @notice Internal function to set a new account on a given role and emit a
* `RoleModified` event if the role holder has changed.
* @param role The role that the account will be set for. Permitted roles are
* deposit manager (0), adjuster (1), and pauser (2).
* @param account The account to set as the designated role bearer.
*/
function _setRole(Role role, address account) internal {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
function _fireTradeEvent(
bool fromReserves,
TradeType tradeType,
address token,
uint256 suppliedAmount,
uint256 receivedAmount,
uint256 retainedAmount
) internal {
uint256 t = uint256(tradeType);
emit Trade(
fromReserves ? address(this) : msg.sender,
t < 2 ? address(_DAI) : (t % 2 == 0 ? address(0) : token),
(t > 1 && t < 4) ? address(_DAI) : (t % 2 == 0 ? token : address(0)),
t < 4 ? address(_DAI) : address(0),
suppliedAmount,
receivedAmount,
retainedAmount
);
}
/**
* @notice Internal view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return A boolean indicating if the caller has the specified role.
*/
function _isRole(Role role) internal view returns (bool hasRole) {
hasRole = msg.sender == _roles[uint256(role)].account;
}
/**
* @notice Internal view function to check whether the given role is paused or
* not.
* @param role The role to check for.
* @return A boolean indicating if the specified role is paused or not.
*/
function _isPaused(Role role) internal view returns (bool paused) {
paused = _roles[uint256(role)].paused;
}
/**
* @notice Internal view function to enforce that the given initial user
* signing key resolves to the given smart wallet when deployed through the
* Dharma Smart Wallet Factory V1. (staging version)
* @param smartWallet address The smart wallet.
* @param initialUserSigningKey address The initial user signing key.
*/
function _isSmartWallet(
address smartWallet, address initialUserSigningKey
) internal pure returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_WALLET_CREATION_CODE_HEADER,
initialUserSigningKey,
_WALLET_CREATION_CODE_FOOTER
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_CREATE2_HEADER, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
function _redeemDDaiIfNecessary(uint256 daiAmountFromReserves) internal {
uint256 daiBalance = _DAI.balanceOf(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_DDAI_EXCHANGER.redeemUnderlyingTo(address(this), additionalDaiRequired);
}
}
function _transferToken(
ERC20Interface token, address to, uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(token.transfer.selector, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer out failed.'
);
}
function _transferEther(address recipient, uint256 etherAmount) internal {
// Send quoted Ether amount to recipient and revert with reason on failure.
(bool ok, ) = recipient.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function _transferInToken(
ERC20Interface token, address from, uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.transferFrom.selector, from, address(this), amount
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer in failed.'
);
}
function _mintDDai(
uint256 dai, bool sendToCaller
) internal returns (uint256 dDai) {
dDai = _DDAI_EXCHANGER.mintTo(
sendToCaller ? msg.sender : address(this), dai
);
}
function _transferAndRedeemDDai(
uint256 daiEquivalentAmount
) internal returns (uint256 totalDDaiRedeemed) {
// Determine dDai to redeem using exchange rate and daiEquivalentAmount.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
totalDDaiRedeemed = (
(daiEquivalentAmount.mul(1e18)).add(exchangeRate.sub(1)) // NOTE: round up
).div(exchangeRate);
// Transfer the dDai from the caller and revert on failure.
_transferInToken(
ERC20Interface(address(_DDAI)), msg.sender, totalDDaiRedeemed
);
// Redeem the dDai for Dai.
_DDAI_EXCHANGER.redeemUnderlyingTo(address(this), daiEquivalentAmount);
}
function _ensureSmartWallet(
address smartWallet, address initialUserSigningKey
) internal pure {
require(
_isSmartWallet(smartWallet, initialUserSigningKey),
"Cannot resolve smart wallet using provided signing key."
);
}
function _createPathAndAmounts(
address start, address end, bool routeThroughEther
) internal pure returns (address[] memory, uint256[] memory) {
uint256 pathLength = routeThroughEther ? 3 : 2;
address[] memory path = new address[](pathLength);
path[0] = start;
if (routeThroughEther) {
path[1] = _WETH;
}
path[pathLength - 1] = end;
return (path, new uint256[](pathLength));
}
function _ensurePrimaryRecipientIsSetAndEmitEvent(
address primaryRecipient, string memory asset, uint256 amount
) internal {
if (primaryRecipient == address(0)) {
revert(string(abi.encodePacked(
asset, " does not have a primary recipient assigned."
)));
}
emit Withdrawal(asset, primaryRecipient, amount);
}
/**
* @notice Modifier that throws if called by any account other than the owner
* or the supplied role, or if the caller is not the owner and the role in
* question is paused.
* @param role The role to require unless the caller is the owner.
*/
modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
}
|
Transfer in sufficient dDai and use it to mint Dai. Trade minted Dai for Ether.
|
function tradeDDaiForEther(
uint256 daiEquivalentAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold, uint256 totalDDaiRedeemed) {
totalDDaiRedeemed = _transferAndRedeemDDai(daiEquivalentAmount);
totalDaiSold = _tradeDaiForEther(
daiEquivalentAmount, quotedEtherAmount, deadline, false
);
}
| 6,602,975 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;
import "./test.sol";
import "../contracts/Dao.sol";
import "../contracts/DaoContract.sol";
interface CheatCodes {
function prank(address) external;
function expectRevert(bytes calldata) external;
}
string constant NullString = "";
bytes constant NullBytes = "";
address constant NullAddress = address(0);
contract DaoTest is DSTest {
CheatCodes cheats = CheatCodes(HEVM_ADDRESS);
Dao dao;
string public gDaoName = "MyDao";
address public gTopicAddress = 0x0000000000000000000000000000000000012345;
uint32 public gMaxUsers = 100000;
uint256 gBatchSize = 1000;
uint32 gAccessUpdateAuthIdentifier = 0x853d9ed4;
uint32 gRemovalAuthIdentifier = 0x04939f12;
uint32 gNotUserIdentifier = 0x51ef2234;
address[] public gUsers = [
address(0x1),
address(0x2),
address(0x3),
address(0x4),
address(0x5),
address(0x6),
address(0x7),
address(0x8),
address(0x9)];
receive() external payable { }
function setUp() public {
dao = new Dao(gDaoName, gTopicAddress, address(this));
}
// =================
// Utility Functions
// =================
function CreateErorrCallData(uint32 _identifier, uint256 _arg1) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1);
}
function CreateErorrCallData(uint32 _identifier, uint256 _arg1, uint256 _arg2) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1, _arg2);
}
function bytesCmp(bytes memory a, bytes memory b) public pure returns(bool){
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
function addAUserNoImpersonateNoRevert(address user, AccessType userLevel) public {
addAUserNoImpersonate(user, userLevel, NullBytes);
}
function addAUserNoImpersonateWithRevert(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUserNoImpersonate(user, userLevel, revertMessage);
}
function addAUserNoImpersonate(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUser(user, userLevel, NullAddress, revertMessage);
}
function addAUserWithImpersonateNoRevert(address user, AccessType userLevel, address impersonateAs) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, NullBytes);
}
function addAUserWithImpersonateWithRevert(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, revertMessage);
}
function addAUserWithImpersonate(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUser(user, userLevel, impersonateAs, revertMessage);
}
function addAUser(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.addUser(param, userLevel);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(userLevel));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeAUserNoImpersonateNoRevert(address user) public {
removeAUserNoImpersonate(user, NullBytes);
}
function removeAUserNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAUserNoImpersonate(user, revertMessage);
}
function removeAUserNoImpersonate(address user, bytes memory revertMessage) public {
removeAUser(user, NullAddress, revertMessage);
}
function removeAUserWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAUserWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAUserWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUserWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAUserWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUser(user, impersonateAs, revertMessage);
}
function removeAUser(address user, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(param);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeUsersNoImpersonateNoRevert(address[] memory users) public {
removeUsersNoImpersonate(users, NullBytes);
}
function removeUsersNoImpersonateWithRevert(address[] memory users, bytes memory revertMessage) public {
removeUsersNoImpersonate(users, revertMessage);
}
function removeUsersNoImpersonate(address[] memory users, bytes memory revertMessage) public {
removeUsers(users, NullAddress, revertMessage);
}
function removeUsersWithImpersonateNoRevert(address[] memory users, address impersonateAs) public {
removeUsersWithImpersonate(users, impersonateAs, NullBytes);
}
function removeUsersWithImpersonateWithRevert(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsersWithImpersonate(users, impersonateAs, revertMessage);
}
function removeUsersWithImpersonate(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsers(users, impersonateAs, revertMessage);
}
function removeUsers(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
AccessType[] memory originalUserLevels = new AccessType[](users.length);
for (uint i = 0; i < users.length; i++){
originalUserLevels[i] = dao.getUser(users[i]);
}
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(users);
if(expectSuccess){
for(uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(0));
}
} else {
for (uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(originalUserLevels[i]));
}
}
}
function removeAnOfficerNoImpersonateNoRevert(address user) public {
removeAnOfficerNoImpersonate(user, NullBytes);
}
function removeAnOfficerNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAnOfficerNoImpersonate(user, revertMessage);
}
function removeAnOfficerNoImpersonate(address user, bytes memory revertMessage) public {
removeAnOfficer(user, NullAddress, revertMessage);
}
function removeAnOfficerWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAnOfficerWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAnOfficerWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficerWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAnOfficerWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficer(user, impersonateAs, revertMessage);
}
function removeAnOfficer(address user, address impersonateAs, bytes memory revertMessage) public {
bool expectSuccess = true;
AccessType origUserLevel = dao.getUser(user);
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeOfficer(user);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function addMaxUsers(bool batched, AccessType level, uint256 batchSize) public {
uint160 i;
uint32 batches;
uint256 numUsersToAdd = gMaxUsers - dao.getUserCount();
// Force non batched if maxUsers is less than batchSize
if (gMaxUsers < batchSize){
batched = false;
}
if(batched){
address[] memory batch = new address[](batchSize);
// Add users in batches minus the last batch witch may be
// not a whole batch of batchSize.
for ( ;i < (numUsersToAdd - numUsersToAdd % batchSize); i++){
// Add user to batch
batch[i%batch.length] = address(i);
// Only send the batch to the contract when its full
if((i%batch.length) == (batch.length-1)){
emit log_named_uint("Batch", batches++);
dao.addUser(batch, level);
}
}
}
// If batched, now send final batch (not full batch)
// If non batched, send all users now in a single batch
if((numUsersToAdd - i) > 0) {
address[] memory finalBatch = new address[](numUsersToAdd - i);
for (uint160 j = 0; i < numUsersToAdd; i++)
{
finalBatch[j++] = address(i);
}
emit log_named_uint("- Batch", batches++);
dao.addUser(finalBatch, level);
}
assertEq(dao.getUserCount(), gMaxUsers);
}
// ===================================================
// ============
// Test getters
// ============
function testGetDaoNameBase() public {
assertEq(dao.getDaoName(), gDaoName);
}
function testGetMaxUsersBase() public {
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testGetTopicAddressBase() public {
assertEq(dao.getTopicAddress(), gTopicAddress);
}
function testGetUserCountBase() public {
assertEq(dao.getUserCount(), 1);
}
function testGetUserBase() public {
assertEq(uint(dao.getUser(address(this))), uint(AccessType.Officer));
}
function testGetBalance() public {
assertEq(dao.getBalance(), 0);
}
// ============
// Test setters
// ============
function testSetMaxUsers() public {
uint32 newMaxUsers = 500000;
dao.setMaxUsers(newMaxUsers);
assertEq(dao.getMaxUsers(), newMaxUsers);
dao.setMaxUsers(gMaxUsers);
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testSetMaxUsersAsNonOwner() public {
cheats.prank(gUsers[1]);
cheats.expectRevert('Only owner is allowed');
dao.setMaxUsers(1234);
}
// ==================================
// Test adding Member user via addUser
// ==================================
function testAddUserMemberAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsMember() public {
// Add gUsers[1] as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test adding Admin user via addUser
// ==================================
function testAddUserAdminAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ====================================
// Test adding Officer user via addUser
// ====================================
function testAddUserOfficerAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
cheats.prank(gUsers[1]);
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =========================================
// Test removing Member user via removeUser
// =========================================
function testRemoveUserMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserMemberAsOfficer() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Admin user via removeUser
// =========================================
function testRemoveUserAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserAdminAsAdmin() public {
// Add gUsers[1] and gUsers[2] as Admins
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Officer user via removeUser
// =========================================
function testRemoveUserOfficerAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsAdmin() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Admin
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Officer
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ============================================
// Test removing Officer user via removeOfficer
// ============================================
function testRemoveOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as the owner
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
// ==========================
// Test Adding MaxUsers Users
// ==========================
function testAddMaxUsersAsMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
}
function testAddMaxUsersAsOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
}
// ============================
// Test Adding MaxUsers+1 Users
// ============================
function testAddMaxUsersPlusAddMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
// ===============================
// Test Adding a Member user twice
// ===============================
function testAddUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ===============================
// Test Adding an Admin user twice
// ===============================
function testAddUserTwiceAdminAsOwner() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceAdminAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Adding an Officer user twice
// =================================
function testAddUserTwiceOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Officer
addAUserNoImpersonateWithRevert(gUsers[1], AccessType.Officer, CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Removing a Member user twice
// =================================
function testRemoveUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// =================================
// Test Removing an Admin user twice
// =================================
function testRemoveUserTwiceAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// ===================================
// Test Removing an Officer user twice
// ===================================
function testRemoveOfficerTwiceAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAnOfficerNoImpersonateWithRevert(gUsers[1], "Not an officer");
assertEq(dao.getUserCount(), 1);
}
// ==============================
// Test Removing users in batches
// ==============================
function testRemoveUsersBatched() public {
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
}
assertEq(dao.getUserCount(), 10);
removeUsersNoImpersonateNoRevert(gUsers);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUsersBatchedNonExistingUser() public {
address[] memory copy = new address[](gUsers.length);
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
copy[i] = gUsers[i];
}
assertEq(dao.getUserCount(), 10);
copy[4] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[4]))));
assertEq(dao.getUserCount(), 10);
copy[4] = gUsers[4];
copy[0] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[0]))));
assertEq(dao.getUserCount(), 10);
copy[0] = gUsers[0];
copy[gUsers.length-1] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[gUsers.length-1]))));
assertEq(dao.getUserCount(), 10);
}
// =================================================
// Test sending/receiving funds to/from the contract
// =================================================
function testDeposit() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(1);
assertEq(dao.getBalance(), 1);
payable(address(dao)).transfer(10);
assertEq(dao.getBalance(), 11);
}
function testWithdrawl() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(10);
uint256 bal_before = address(this).balance;
dao.transferHbar(payable(address(this)), 1);
assertEq(bal_before, address(this).balance - 1);
}
function testWithdrawlRevert() public {
assertEq(dao.getBalance(), 0);
cheats.expectRevert("");
dao.transferHbar(payable(address(this)), 1);
}
// ================================
// Test promoting a Member to Admin
// ================================
function testPromoteMemberToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting a Member to Officer
// ==================================
function testPromoteMemberToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting an Admin to Officer
// ==================================
function testPromoteAdminToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test demoting an Officer to Amdin
// =================================
function testDemoteOfficerToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test demoting an Officer to Member
// ==================================
function testDemoteOfficerToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ================================
// Test demoting an Admin to Member
// ================================
function testDemoteAdminToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
}
|
Add gUsers[1] as an Officer Add gUsers[2] as an Admin Remove gUsers[2] as gUsers[1] who is an Officer
|
function testRemoveUserAdminAsOfficer() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
| 14,053,778 |
./full_match/1/0x992F6c414A6DA6A7470dfB9D61eFc6639e9fbb0E/sources/browser/MerkleThreeVerification.sol
|
internal helpers for convert address
|
function addressToString(address x) internal pure returns (string memory) {
bytes memory b = new bytes(20);
for (uint i = 0; i < 20; i++)
b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
return string(b);
}
| 2,929,482 |
// SPDX-License-Identifier: MIT
// Author: Pagzi Tech Inc | 2022
// Pagzi Pass - Exclusive | 2022
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract PagziPass is Context, ERC165, IERC721, IERC721Metadata, Ownable {
using Address for address;
using Strings for uint256;
// Token name and symbol
string private _name = "Pagzi Pass";
string private _symbol = "PAGZI";
mapping(uint => uint) private _availableTokens;
uint256 private _numAvailableTokens = 5;
uint256 private _maxSupply = 5;
// 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;
//allowlist settings
bytes32 public merkleRoot = 0x5a1d22879f743d4382e9541e9c62485565a9054c85d711297fd8450245248c89;
mapping(address => bool) public claimed;
//sale settings
uint256 public cost = 0.001 ether;
//backend settings
string public baseURI;
address internal founder = 0xF4617b57ad853f4Bc2Ce3f06C0D74958c240633c;
//proxy access and freezing
mapping(address => bool) public projectProxy;
bool public frozen;
//date variables
uint256 public publicDate = 1651336697;
//mint passes/claims
address public proxyAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
//royalty settings
uint256 public royaltyFee = 10000;
modifier checkDate() {
require((publicDate < block.timestamp),"Allowlist sale is not yet!");
_;
}
modifier checkPrice() {
require(msg.value == cost , "Check sent funds!");
_;
}
/**
* @dev Initializes the contract by minting the #0 to Doug and setting the baseURI ;)
*/
constructor() {
_mintAtIndex(founder,0);
baseURI = "https://pagzipass.nftapi.art/meta/";
}
// external
function mint(bytes32[] calldata _merkleProof) external payable checkPrice checkDate {
// Verify allowlist requirements
require(claimed[msg.sender] != true, "Address has no allowance!");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid merkle proof!");
require(_numAvailableTokens > 1, "No tokens left!");
_mintRandom(msg.sender);
claimed[msg.sender] = true;
}
/**
* @dev See {ERC-2981-royaltyInfo}.
*/
function royaltyInfo(uint256, uint256 value) external view
returns (address receiver, uint256 royaltyAmount){
require(royaltyFee > 0, "ERC-2981: Royalty not set!");
return (founder, (value * royaltyFee) / 10000);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == 0x2a55205a /* ERC-2981 royaltyInfo() */ ||
super.supportsInterface(interfaceId);
}
function totalSupply() public view virtual returns (uint256) {
return _maxSupply - _numAvailableTokens;
}
function maxSupply() public view virtual returns (uint256) {
return _maxSupply;
}
/**
* @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 {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = PagziPass.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-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 = PagziPass.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _mintIdWithoutBalanceUpdate(address to, uint256 tokenId) private {
_beforeTokenTransfer(address(0), to, tokenId);
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
function _mintRandom(address to) internal virtual {
uint updatedNumAvailableTokens = _numAvailableTokens;
uint256 tokenId = getRandomAvailableTokenId(to, updatedNumAvailableTokens);
_mintIdWithoutBalanceUpdate(to, tokenId);
--updatedNumAvailableTokens;
_numAvailableTokens = updatedNumAvailableTokens;
_balances[to] += 1;
}
function getRandomAvailableTokenId(address to, uint updatedNumAvailableTokens) internal returns (uint256) {
uint256 randomNum = uint256(
keccak256(
abi.encode(
to,
tx.gasprice,
block.number,
block.timestamp,
block.difficulty,
blockhash(block.number - 1),
address(this),
updatedNumAvailableTokens
)
)
);
uint256 randomIndex = randomNum % updatedNumAvailableTokens;
return getAvailableTokenAtIndex(randomIndex, updatedNumAvailableTokens);
}
function getAvailableTokenAtIndex(uint256 indexToUse, uint updatedNumAvailableTokens) internal returns (uint256) {
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 result;
if (valAtIndex == 0) {
// This means the index itself is still an available token
result = indexToUse;
} else {
// This means the index itself is not an available token, but the val at that index is.
result = valAtIndex;
}
uint256 lastIndex = updatedNumAvailableTokens - 1;
if (indexToUse != lastIndex) {
uint256 lastValInArray = _availableTokens[lastIndex];
if (lastValInArray == 0) {
_availableTokens[indexToUse] = lastIndex;
} else {
_availableTokens[indexToUse] = lastValInArray;
delete _availableTokens[lastIndex];
}
}
return result;
}
function _mintAtIndex(address to, uint index) internal virtual {
uint tokenId = getAvailableTokenAtIndex(index, _numAvailableTokens);
--_numAvailableTokens;
_mintIdWithoutBalanceUpdate(to, tokenId);
_balances[to] += 1;
}
/**
* @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(PagziPass.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(PagziPass.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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
//only owner
function gift(uint256[] calldata quantity, address[] calldata recipient) external onlyOwner{
require(quantity.length == recipient.length, "Invalid data" );
uint256 totalQuantity;
for(uint256 i = 0; i < quantity.length; ++i){
totalQuantity += quantity[i];
}
require(_numAvailableTokens >= totalQuantity, "ERC721: minting more tokens than available");
for(uint256 i = 0; i < recipient.length; ++i){
for(uint256 j = 1; j <= quantity[i]; ++j){
_mintRandom(recipient[i]);
}
}
delete totalQuantity;
}
function setSupply(uint256 _supply) external onlyOwner {
_maxSupply = _supply;
}
function setAvailibility(uint256 _supply) external onlyOwner {
_numAvailableTokens = _supply;
}
function setCost(uint256 _cost) external onlyOwner {
cost = _cost;
}
function setPublicDate(uint256 _publicDate) external onlyOwner {
publicDate = _publicDate;
}
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
merkleRoot = _merkleRoot;
}
function switchProxy(address _proxyAddress) public onlyOwner {
projectProxy[_proxyAddress] = !projectProxy[_proxyAddress];
}
function setProxy(address _proxyAddress) external onlyOwner {
proxyAddress = _proxyAddress;
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "Token does not exist.");
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
function tokensOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory allTokens = new uint256[](tokenCount);
uint256 j = 0;
for(uint256 i; i < _maxSupply; i++ ){
address owner = _owners[i];
if(_owner == owner){
allTokens[j] = (i);
j++;
if(j == tokenCount) return allTokens;
}
}
return allTokens;
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], data_);
}
}
function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool){
for(uint256 i; i < _tokenIds.length; ++i ){
if(_owners[_tokenIds[i]] != account)
return false;
}
return true;
}
function isApprovedForAll(address _owner, address operator) public view override(IERC721) returns (bool) {
//Free listing on OpenSea by granting access to their proxy wallet. This can be removed in case of a breach on OS.
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyAddress);
if (address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator]) return true;
return isApprovedForAll(_owner, operator);
}
//ERC-2981 Royalty Implementation
function setRoyalty(address _royaltyAddr, uint256 _royaltyFee) public onlyOwner {
require(_royaltyFee < 10001, "ERC-2981: Royalty too high!");
founder = _royaltyAddr;
royaltyFee = _royaltyFee;
}
function freeze() external onlyOwner {
frozen = !frozen;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(founder).transfer(balance);
}
}
contract OwnableDelegateProxy { }
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
/**
* @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;
/**
* @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;
/**
* @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);
}
|
external Verify allowlist requirements
|
function mint(bytes32[] calldata _merkleProof) external payable checkPrice checkDate {
require(claimed[msg.sender] != true, "Address has no allowance!");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid merkle proof!");
require(_numAvailableTokens > 1, "No tokens left!");
_mintRandom(msg.sender);
claimed[msg.sender] = true;
}
| 1,302,094 |
/* solhint-disable func-order */
pragma solidity ^0.4.24;
import "./BimodalLib.sol";
import "./MerkleVerifier.sol";
import "./SafeMath/SafeMathLib32.sol";
import "./SafeMath/SafeMathLib256.sol";
/**
* This library contains the challenge-response implementations of NOCUST.
*/
library ChallengeLib {
using SafeMathLib256 for uint256;
using SafeMathLib32 for uint32;
using BimodalLib for BimodalLib.Ledger;
// EVENTS
event ChallengeIssued(address indexed token, address indexed recipient, address indexed sender);
event StateUpdate(
address indexed token,
address indexed account,
uint256 indexed eon,
uint64 trail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
bytes32 activeStateChecksum,
bytes32 passiveChecksum,
bytes32 r, bytes32 s, uint8 v
);
// Validation
function verifyProofOfExclusiveAccountBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20 token,
address holder,
bytes32[2] activeStateChecksum_passiveTransfersRoot, // solhint-disable func-param-name-mixedcase
uint64 trail,
uint256[3] eonPassiveMark,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2] LR // solhint-disable func-param-name-mixedcase
)
public
view
returns (bool)
{
BimodalLib.Checkpoint memory checkpoint = ledger.checkpoints[eonPassiveMark[0].mod(ledger.EONS_KEPT)];
require(eonPassiveMark[0] == checkpoint.eonNumber, 'r');
// activeStateChecksum is set to the account node.
activeStateChecksum_passiveTransfersRoot[0] = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(holder)),
keccak256(abi.encodePacked(
activeStateChecksum_passiveTransfersRoot[1], // passiveTransfersRoot
eonPassiveMark[1],
eonPassiveMark[2])),
activeStateChecksum_passiveTransfersRoot[0] // activeStateChecksum
));
// the interval allotment is set to form the leaf
activeStateChecksum_passiveTransfersRoot[0] = keccak256(abi.encodePacked(
LR[0], activeStateChecksum_passiveTransfersRoot[0], LR[1]
));
// This calls the merkle verification procedure, which returns the
// checkpoint allotment size
uint64 tokenTrail = ledger.tokenToTrail[token];
LR[0] = MerkleVerifier.verifyProofOfExclusiveBalanceAllotment(
trail,
tokenTrail,
activeStateChecksum_passiveTransfersRoot[0],
checkpoint.merkleRoot,
allotmentChain,
membershipChain,
values,
LR);
// The previous allotment size of the target eon is reconstructed from the
// deposits and withdrawals performed so far and the current balance.
LR[1] = address(this).balance;
if (token != address(this)) {
require(
tokenTrail != 0,
't');
LR[1] = token.balanceOf(this);
}
// Credit back confirmed withdrawals that were performed since target eon
for (tokenTrail = 0; tokenTrail < ledger.EONS_KEPT; tokenTrail++) {
if (ledger.confirmedWithdrawals[token][tokenTrail].eon >= eonPassiveMark[0]) {
LR[1] = LR[1].add(ledger.confirmedWithdrawals[token][tokenTrail].amount);
}
}
// Debit deposits performed since target eon
for (tokenTrail = 0; tokenTrail < ledger.EONS_KEPT; tokenTrail++) {
if (ledger.deposits[token][tokenTrail].eon >= eonPassiveMark[0]) {
LR[1] = LR[1].sub(ledger.deposits[token][tokenTrail].amount);
}
}
// Debit withdrawals pending since prior eon
LR[1] = LR[1].sub(ledger.getPendingWithdrawalsAtEon(token, eonPassiveMark[0].sub(1)));
// Require that the reconstructed allotment matches the proof allotment
require(
LR[0] <= LR[1],
'b');
return true;
}
function verifyProofOfActiveStateUpdateAgreement(
ERC20 token,
address holder,
uint64 trail,
uint256 eon,
bytes32 txSetRoot,
uint256[2] deltas,
address attester,
bytes32 r,
bytes32 s,
uint8 v
)
public
view
returns (bytes32 checksum)
{
checksum = MerkleVerifier.activeStateUpdateChecksum(token, holder, trail, eon, txSetRoot, deltas);
require(attester == BimodalLib.signedMessageECRECOVER(checksum, r, s, v), 'A');
}
function verifyWithdrawalAuthorization(
ERC20 token,
address holder,
uint256 expiry,
uint256 amount,
address attester,
bytes32 r,
bytes32 s,
uint8 v
)
public
view
returns (bool)
{
bytes32 checksum = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(holder)),
expiry,
amount));
require(attester == BimodalLib.signedMessageECRECOVER(checksum, r, s, v), 'a');
return true;
}
// Challenge Lifecycle Methods
/**
* This method increments the live challenge counter and emits and event
* containing the challenge index.
*/
function markChallengeLive(
BimodalLib.Ledger storage ledger,
ERC20 token,
address recipient,
address sender
)
private
{
require(ledger.currentEra() > ledger.BLOCKS_PER_EPOCH);
uint256 eon = ledger.currentEon();
BimodalLib.Checkpoint storage checkpoint = ledger.getOrCreateCheckpoint(eon, eon);
checkpoint.liveChallenges = checkpoint.liveChallenges.add(1);
emit ChallengeIssued(token, recipient, sender);
}
/**
* This method clears all the data in a Challenge structure and decrements the
* live challenge counter.
*/
function clearChallenge(
BimodalLib.Ledger storage ledger,
BimodalLib.Challenge storage challenge
)
private
{
BimodalLib.Checkpoint storage checkpoint = ledger.getOrCreateCheckpoint(
challenge.initialStateEon.add(1),
ledger.currentEon());
checkpoint.liveChallenges = checkpoint.liveChallenges.sub(1);
challenge.challengeType = BimodalLib.ChallengeType.NONE;
challenge.block = 0;
// challenge.initialStateEon = 0;
challenge.initialStateBalance = 0;
challenge.deltaHighestSpendings = 0;
challenge.deltaHighestGains = 0;
challenge.finalStateBalance = 0;
challenge.deliveredTxNonce = 0;
challenge.trailIdentifier = 0;
}
/**
* This method marks a challenge as having been successfully answered only if
* the response was provided in time.
*/
function markChallengeAnswered(
BimodalLib.Ledger storage ledger,
BimodalLib.Challenge storage challenge
)
private
{
uint256 eon = ledger.currentEon();
require(
challenge.challengeType != BimodalLib.ChallengeType.NONE &&
block.number.sub(challenge.block) < ledger.BLOCKS_PER_EPOCH &&
(
challenge.initialStateEon == eon.sub(1) ||
(challenge.initialStateEon == eon.sub(2) && ledger.currentEra() < ledger.BLOCKS_PER_EPOCH)
)
);
clearChallenge(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== STATE UPDATE Challenge
// ========================================================================
// ========================================================================
// ========================================================================
/**
* This method initiates the fields of the Challenge struct to hold a state
* update challenge.
*/
function initStateUpdateChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
uint256 owed,
uint256[2] spentGained,
uint64 trail
)
private
{
BimodalLib.Challenge storage challengeEntry = ledger.challengeBook[token][msg.sender][msg.sender];
require(challengeEntry.challengeType == BimodalLib.ChallengeType.NONE);
require(challengeEntry.initialStateEon < ledger.currentEon().sub(1));
challengeEntry.initialStateEon = ledger.currentEon().sub(1);
challengeEntry.initialStateBalance = owed;
challengeEntry.deltaHighestSpendings = spentGained[0];
challengeEntry.deltaHighestGains = spentGained[1];
challengeEntry.trailIdentifier = trail;
challengeEntry.challengeType = BimodalLib.ChallengeType.STATE_UPDATE;
challengeEntry.block = block.number;
markChallengeLive(ledger, token, msg.sender, msg.sender);
}
/**
* This method checks that the updated balance is at least as much as the
* expected balance.
*/
function checkStateUpdateBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
BimodalLib.Challenge storage challenge,
uint256[2] LR, // solhint-disable func-param-name-mixedcase
uint256[2] spentGained,
uint256 passivelyReceived
)
private
view
{
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(token, msg.sender);
uint256 incoming = spentGained[1] // actively received in commit chain
.add(deposits)
.add(passivelyReceived);
uint256 outgoing = spentGained[0] // actively spent in commit chain
.add(withdrawals);
// This verification is modified to permit underflow of expected balance
// since a client can choose to zero the `challenge.initialStateBalance`
require(
challenge.initialStateBalance
.add(incoming)
<=
LR[1].sub(LR[0]) // final balance allotment
.add(outgoing)
,
'B');
}
function challengeStateUpdateWithProofOfExclusiveBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20 token,
bytes32[2] checksums,
uint64 trail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] value,
uint256[2][3] lrDeltasPassiveMark,
bytes32[3] rsTxSetRoot,
uint8 v
)
public
/* payable */
/* onlyWithFairReimbursement(ledger) */
{
uint256 previousEon = ledger.currentEon().sub(1);
address operator = ledger.operator;
// The hub must have committed to this state update
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) {
verifyProofOfActiveStateUpdateAgreement(
token,
msg.sender,
trail,
previousEon,
rsTxSetRoot[2],
lrDeltasPassiveMark[1],
operator,
rsTxSetRoot[0], rsTxSetRoot[1], v);
}
initStateUpdateChallenge(
ledger,
token,
lrDeltasPassiveMark[0][1].sub(lrDeltasPassiveMark[0][0]),
lrDeltasPassiveMark[1],
trail);
// The initial state must have been ratified in the commitment
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
msg.sender,
checksums,
trail,
[previousEon, lrDeltasPassiveMark[2][0], lrDeltasPassiveMark[2][1]],
allotmentChain,
membershipChain,
value,
lrDeltasPassiveMark[0]));
}
function challengeStateUpdateWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
bytes32 txSetRoot,
uint64 trail,
uint256[2] deltas,
bytes32 r,
bytes32 s,
uint8 v
)
public
/* payable */
/* TODO calculate exact addition */
/* onlyWithSkewedReimbursement(ledger, 25) */
{
// The hub must have committed to this transition
verifyProofOfActiveStateUpdateAgreement(
token,
msg.sender,
trail,
ledger.currentEon().sub(1),
txSetRoot,
deltas,
ledger.operator,
r, s, v);
initStateUpdateChallenge(ledger, token, 0, deltas, trail);
}
function answerStateUpdateChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
address issuer,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark, // [ [L, R], Deltas ]
bytes32[6] rSrStxSetRootChecksum,
uint8[2] v
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][issuer][issuer];
require(challenge.challengeType == BimodalLib.ChallengeType.STATE_UPDATE);
// Transition must have been approved by issuer
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) {
rSrStxSetRootChecksum[0] = verifyProofOfActiveStateUpdateAgreement(
token,
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
rSrStxSetRootChecksum[4], // txSetRoot
lrDeltasPassiveMark[1], // deltas
issuer,
rSrStxSetRootChecksum[0], // R[0]
rSrStxSetRootChecksum[1], // S[0]
v[0]);
address operator = ledger.operator;
rSrStxSetRootChecksum[1] = verifyProofOfActiveStateUpdateAgreement(
token,
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
rSrStxSetRootChecksum[4], // txSetRoot
lrDeltasPassiveMark[1], // deltas
operator,
rSrStxSetRootChecksum[2], // R[1]
rSrStxSetRootChecksum[3], // S[1]
v[1]);
require(rSrStxSetRootChecksum[0] == rSrStxSetRootChecksum[1], 'u');
} else {
rSrStxSetRootChecksum[0] = bytes32(0);
}
// Transition has to be at least as recent as submitted one
require(
lrDeltasPassiveMark[1][0] >= challenge.deltaHighestSpendings &&
lrDeltasPassiveMark[1][1] >= challenge.deltaHighestGains,
'x');
// Transition has to have been properly applied
checkStateUpdateBalance(
ledger,
token,
challenge,
lrDeltasPassiveMark[0], // LR
lrDeltasPassiveMark[1], // deltas
lrDeltasPassiveMark[2][0]); // passive amount
// Truffle crashes when trying to interpret this event in some cases.
emit StateUpdate(
token,
issuer,
challenge.initialStateEon.add(1),
challenge.trailIdentifier,
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark,
rSrStxSetRootChecksum[0], // activeStateChecksum
rSrStxSetRootChecksum[5], // passiveAcceptChecksum
rSrStxSetRootChecksum[2], // R[1]
rSrStxSetRootChecksum[3], // S[1]
v[1]);
// Proof of stake must be ratified in the checkpoint
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
issuer,
[rSrStxSetRootChecksum[0], rSrStxSetRootChecksum[5]], // activeStateChecksum, passiveAcceptChecksum
challenge.trailIdentifier,
[
challenge.initialStateEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1]
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0]), // LR
'c');
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== ACTIVE DELIVERY Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function initTransferDeliveryChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
address sender,
address recipient,
uint256 amount,
uint256 txNonce,
uint64 trail
)
private
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][recipient][sender];
require(challenge.challengeType == BimodalLib.ChallengeType.NONE);
require(challenge.initialStateEon < ledger.currentEon().sub(1));
challenge.challengeType = BimodalLib.ChallengeType.TRANSFER_DELIVERY;
challenge.initialStateEon = ledger.currentEon().sub(1);
challenge.deliveredTxNonce = txNonce;
challenge.block = block.number;
challenge.trailIdentifier = trail;
challenge.finalStateBalance = amount;
markChallengeLive(
ledger,
token,
recipient,
sender);
}
function challengeTransferDeliveryWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint256[2] nonceAmount,
uint64[3] trails,
bytes32[] chain,
uint256[2] deltas,
bytes32[3] rsTxSetRoot,
uint8 v
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
require(msg.sender == SR[0] || msg.sender == SR[1], 'd');
// Require hub to have committed to transition
verifyProofOfActiveStateUpdateAgreement(
token,
SR[0],
trails[0],
ledger.currentEon().sub(1),
rsTxSetRoot[2],
deltas,
ledger.operator,
rsTxSetRoot[0], rsTxSetRoot[1], v);
rsTxSetRoot[0] = MerkleVerifier.transferChecksum(
SR[1],
nonceAmount[1], // amount
trails[2],
nonceAmount[0]); // nonce
// Require tx to exist in transition
require(MerkleVerifier.verifyProofOfMembership(
trails[1],
chain,
rsTxSetRoot[0], // transferChecksum
rsTxSetRoot[2]), // txSetRoot
'e');
initTransferDeliveryChallenge(
ledger,
token,
SR[0], // senderAddress
SR[1], // recipientAddress
nonceAmount[1], // amount
nonceAmount[0], // nonce
trails[2]); // recipientTrail
}
function answerTransferDeliveryChallengeWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
bytes32[2] txSetRootChecksum,
bytes32[] txChain
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][SR[1]][SR[0]];
require(challenge.challengeType == BimodalLib.ChallengeType.TRANSFER_DELIVERY);
// Assert that the challenged transaction belongs to the transfer set
require(MerkleVerifier.verifyProofOfMembership(
transferMembershipTrail,
txChain,
MerkleVerifier.transferChecksum(
SR[0],
challenge.finalStateBalance, // amount
challenge.trailIdentifier, // recipient trail
challenge.deliveredTxNonce),
txSetRootChecksum[0])); // txSetRoot
// Require committed transition to include transfer
txSetRootChecksum[0] = MerkleVerifier.activeStateUpdateChecksum(
token,
SR[1],
challenge.trailIdentifier,
challenge.initialStateEon,
txSetRootChecksum[0], // txSetRoot
lrDeltasPassiveMark[1]); // Deltas
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[1], // recipient
txSetRootChecksum, // [activeStateChecksum, passiveChecksum]
challenge.trailIdentifier,
[
challenge.initialStateEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0])); // LR
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== PASSIVE DELIVERY Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function challengeTransferDeliveryWithProofOfPassiveStateUpdate(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
bytes32[2] txSetRootChecksum,
uint64[3] senderTransferRecipientTrails,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][4] lrDeltasPassiveMarkDummyAmount,
bytes32[] transferMembershipChain
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
require(msg.sender == SR[0] || msg.sender == SR[1], 'd');
lrDeltasPassiveMarkDummyAmount[3][0] = ledger.currentEon().sub(1); // previousEon
// Assert that the challenged transaction ends the transfer set
require(MerkleVerifier.verifyProofOfMembership(
senderTransferRecipientTrails[1], // transferMembershipTrail
transferMembershipChain,
MerkleVerifier.transferChecksum(
SR[1], // recipientAddress
lrDeltasPassiveMarkDummyAmount[3][1], // amount
senderTransferRecipientTrails[2], // recipientTrail
2 ** 256 - 1), // nonce
txSetRootChecksum[0]), // txSetRoot
'e');
// Require committed transition to include transfer
txSetRootChecksum[0] = MerkleVerifier.activeStateUpdateChecksum(
token,
SR[0], // senderAddress
senderTransferRecipientTrails[0], // senderTrail
lrDeltasPassiveMarkDummyAmount[3][0], // previousEon
txSetRootChecksum[0], // txSetRoot
lrDeltasPassiveMarkDummyAmount[1]); // Deltas
// Assert that this transition was used to update the sender's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[0], // senderAddress
txSetRootChecksum, // [activeStateChecksum, passiveChecksum]
senderTransferRecipientTrails[0], // senderTrail
[
lrDeltasPassiveMarkDummyAmount[3][0].add(1), // eonNumber
lrDeltasPassiveMarkDummyAmount[2][0], // passiveAmount
lrDeltasPassiveMarkDummyAmount[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMarkDummyAmount[0])); // LR
initTransferDeliveryChallenge(
ledger,
token,
SR[0], // sender
SR[1], // recipient
lrDeltasPassiveMarkDummyAmount[3][1], // amount
uint256(keccak256(abi.encodePacked(lrDeltasPassiveMarkDummyAmount[2][1], uint256(2 ** 256 - 1)))), // mark (nonce)
senderTransferRecipientTrails[2]); // recipientTrail
}
function answerTransferDeliveryChallengeWithProofOfPassiveStateUpdate(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrPassiveMarkPositionNonce,
bytes32[2] checksums,
bytes32[] txChainValues
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][SR[1]][SR[0]];
require(challenge.challengeType == BimodalLib.ChallengeType.TRANSFER_DELIVERY);
require(
challenge.deliveredTxNonce ==
uint256(keccak256(abi.encodePacked(lrPassiveMarkPositionNonce[2][0], lrPassiveMarkPositionNonce[2][1])))
);
// Assert that the challenged transaction belongs to the passively delivered set
require(
MerkleVerifier.verifyProofOfPassiveDelivery(
transferMembershipTrail,
MerkleVerifier.transferChecksum( // node
SR[0], // sender
challenge.finalStateBalance, // amount
challenge.trailIdentifier, // recipient trail
challenge.deliveredTxNonce),
checksums[1], // passiveChecksum
txChainValues,
[lrPassiveMarkPositionNonce[2][0], lrPassiveMarkPositionNonce[2][0].add(challenge.finalStateBalance)])
<=
lrPassiveMarkPositionNonce[1][0]);
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[1], // recipient
checksums, // [activeStateChecksum, passiveChecksum]
challenge.trailIdentifier, // recipientTrail
[
challenge.initialStateEon.add(1), // eonNumber
lrPassiveMarkPositionNonce[1][0], // passiveAmount
lrPassiveMarkPositionNonce[1][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrPassiveMarkPositionNonce[0])); // LR
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== SWAP Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function initSwapEnactmentChallenge(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
uint256[4] updatedSpentGainedPassive,
uint256[4] sellBuyBalanceNonce,
uint64 recipientTrail
)
private
{
ERC20 conduit = ERC20(address(keccak256(abi.encodePacked(tokens[0], tokens[1]))));
BimodalLib.Challenge storage challenge = ledger.challengeBook[conduit][msg.sender][msg.sender];
require(challenge.challengeType == BimodalLib.ChallengeType.NONE);
require(challenge.initialStateEon < ledger.currentEon().sub(1));
challenge.initialStateEon = ledger.currentEon().sub(1);
challenge.deliveredTxNonce = sellBuyBalanceNonce[3];
challenge.challengeType = BimodalLib.ChallengeType.SWAP_ENACTMENT;
challenge.block = block.number;
challenge.trailIdentifier = recipientTrail;
challenge.deltaHighestSpendings = sellBuyBalanceNonce[0];
challenge.deltaHighestGains = sellBuyBalanceNonce[1];
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(tokens[0], msg.sender);
challenge.initialStateBalance =
sellBuyBalanceNonce[2] // allotment from eon e - 1
.add(updatedSpentGainedPassive[2]) // gained
.add(updatedSpentGainedPassive[3]) // passively delivered
.add(deposits)
.sub(updatedSpentGainedPassive[1]) // spent
.sub(withdrawals);
challenge.finalStateBalance = updatedSpentGainedPassive[0];
require(challenge.finalStateBalance >= challenge.initialStateBalance, 'd');
markChallengeLive(ledger, conduit, msg.sender, msg.sender);
}
function challengeSwapEnactmentWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
uint64[3] senderTransferRecipientTrails, // senderTransferRecipientTrails
bytes32[] allotmentChain,
bytes32[] membershipChain,
bytes32[] txChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
uint256[4] sellBuyBalanceNonce,
bytes32[3] txSetRootChecksumDummy
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
// Require swap to exist in transition
txSetRootChecksumDummy[2] = MerkleVerifier.swapOrderChecksum(
tokens,
senderTransferRecipientTrails[2],
sellBuyBalanceNonce[0], // sell
sellBuyBalanceNonce[1], // buy
sellBuyBalanceNonce[2], // balance
sellBuyBalanceNonce[3]); // nonce
require(MerkleVerifier.verifyProofOfMembership(
senderTransferRecipientTrails[1],
txChain,
txSetRootChecksumDummy[2], // swapOrderChecksum
txSetRootChecksumDummy[0]), // txSetRoot
'e');
uint256 previousEon = ledger.currentEon().sub(1);
// Require committed transition to include swap
txSetRootChecksumDummy[2] = MerkleVerifier.activeStateUpdateChecksum(
tokens[0],
msg.sender,
senderTransferRecipientTrails[0],
previousEon,
txSetRootChecksumDummy[0],
lrDeltasPassiveMark[1]); // deltas
uint256 updatedBalance = lrDeltasPassiveMark[0][1].sub(lrDeltasPassiveMark[0][0]);
// The state must have been ratified in the commitment
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
tokens[0],
msg.sender,
[txSetRootChecksumDummy[2], txSetRootChecksumDummy[1]], // [activeStateChecksum, passiveChecksum]
senderTransferRecipientTrails[0],
[
previousEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0])); // LR
initSwapEnactmentChallenge(
ledger,
tokens,
[
updatedBalance, // updated
lrDeltasPassiveMark[1][0], // spent
lrDeltasPassiveMark[1][1], // gained
lrDeltasPassiveMark[2][0]], // passiveAmount
sellBuyBalanceNonce,
senderTransferRecipientTrails[2]);
}
/**
* This method just calculates the total expected balance.
*/
function calculateSwapConsistencyBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
uint256[2] deltas,
uint256 passiveAmount,
uint256 balance
)
private
view
returns (uint256)
{
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(token, msg.sender);
return balance
.add(deltas[1]) // gained
.add(passiveAmount) // passively delivered
.add(deposits)
.sub(withdrawals)
.sub(deltas[0]); // spent
}
/**
* This method calculates the balance expected to be credited in return for that
* debited in another token according to the swapping price and is adjusted to
* ignore numerical errors up to 2 decimal places.
*/
function verifySwapConsistency(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
BimodalLib.Challenge challenge,
uint256[2] LR, // solhint-disable func-param-name-mixedcase
uint256[2] deltas,
uint256 passiveAmount,
uint256 balance
)
private
view
returns (bool)
{
balance = calculateSwapConsistencyBalance(ledger, tokens[1], deltas, passiveAmount, balance);
require(LR[1].sub(LR[0]) >= balance);
uint256 taken = challenge.deltaHighestSpendings // sell amount
.sub(challenge.finalStateBalance.sub(challenge.initialStateBalance)); // refund
uint256 given = LR[1].sub(LR[0]) // recipient allotment
.sub(balance); // authorized allotment
return taken.mul(challenge.deltaHighestGains).div(100) >= challenge.deltaHighestSpendings.mul(given).div(100);
}
function answerSwapChallengeWithProofOfExclusiveBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
address issuer,
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
bytes32[] txChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
uint256 balance,
bytes32[3] txSetRootChecksumDummy
)
public
{
ERC20 conduit = ERC20(address(keccak256(abi.encodePacked(tokens[0], tokens[1]))));
BimodalLib.Challenge storage challenge = ledger.challengeBook[conduit][issuer][issuer];
require(challenge.challengeType == BimodalLib.ChallengeType.SWAP_ENACTMENT);
// Assert that the challenged swap belongs to the transition
txSetRootChecksumDummy[2] = MerkleVerifier.swapOrderChecksum(
tokens,
challenge.trailIdentifier, // recipient trail
challenge.deltaHighestSpendings, // sell amount
challenge.deltaHighestGains, // buy amount
balance, // starting balance
challenge.deliveredTxNonce);
require(MerkleVerifier.verifyProofOfMembership(
transferMembershipTrail,
txChain,
txSetRootChecksumDummy[2], // order checksum
txSetRootChecksumDummy[0]), 'M'); // txSetRoot
// Require committed transition to include swap
txSetRootChecksumDummy[2] = MerkleVerifier.activeStateUpdateChecksum(
tokens[1],
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
txSetRootChecksumDummy[0], // txSetRoot
lrDeltasPassiveMark[1]); // deltas
if (balance != 2 ** 256 - 1) {
require(verifySwapConsistency(
ledger,
tokens,
challenge,
lrDeltasPassiveMark[0],
lrDeltasPassiveMark[1],
lrDeltasPassiveMark[2][0],
balance),
'v');
}
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
tokens[1],
issuer,
[txSetRootChecksumDummy[2], txSetRootChecksumDummy[1]], // activeStateChecksum, passiveChecksum
challenge.trailIdentifier,
[challenge.initialStateEon.add(1), lrDeltasPassiveMark[2][0], lrDeltasPassiveMark[2][1]],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0]), // LR
's');
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== WITHDRAWAL Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function slashWithdrawalWithProofOfMinimumAvailableBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
address withdrawer,
uint256[2] markerEonAvailable,
bytes32[2] rs,
uint8 v
)
public
returns (uint256[2] amounts)
{
uint256 latestEon = ledger.currentEon();
require(
latestEon < markerEonAvailable[0].add(3),
'm');
bytes32 checksum = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(withdrawer)),
markerEonAvailable[0],
markerEonAvailable[1]
));
require(withdrawer == BimodalLib.signedMessageECRECOVER(checksum, rs[0], rs[1], v));
BimodalLib.Wallet storage entry = ledger.walletBook[token][withdrawer];
BimodalLib.Withdrawal[] storage withdrawals = entry.withdrawals;
for (uint32 i = 1; i <= withdrawals.length; i++) {
BimodalLib.Withdrawal storage withdrawal = withdrawals[withdrawals.length.sub(i)];
if (withdrawal.eon.add(1) < latestEon) {
break;
} else if (withdrawal.eon == latestEon.sub(1)) {
amounts[0] = amounts[0].add(withdrawal.amount);
} else if (withdrawal.eon == latestEon) {
amounts[1] = amounts[1].add(withdrawal.amount);
}
}
require(amounts[0].add(amounts[1]) > markerEonAvailable[1]);
withdrawals.length = withdrawals.length.sub(i.sub(1)); // i >= 1
if (amounts[1] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon, latestEon, amounts[1]);
ledger.appendOperationToEonAccumulator(
latestEon,
token,
withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[1]);
}
if (amounts[0] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon.sub(1), latestEon, amounts[0]);
ledger.appendOperationToEonAccumulator(
latestEon.sub(1),
token, withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[0]);
}
}
}
|
======================================================================== ======================================================================== ======================================================================== ==================================== WITHDRAWAL Challenge ======================================================================== ======================================================================== ========================================================================
|
function slashWithdrawalWithProofOfMinimumAvailableBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
address withdrawer,
uint256[2] markerEonAvailable,
bytes32[2] rs,
uint8 v
)
public
returns (uint256[2] amounts)
{
uint256 latestEon = ledger.currentEon();
require(
latestEon < markerEonAvailable[0].add(3),
'm');
bytes32 checksum = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(withdrawer)),
markerEonAvailable[0],
markerEonAvailable[1]
));
require(withdrawer == BimodalLib.signedMessageECRECOVER(checksum, rs[0], rs[1], v));
BimodalLib.Wallet storage entry = ledger.walletBook[token][withdrawer];
BimodalLib.Withdrawal[] storage withdrawals = entry.withdrawals;
for (uint32 i = 1; i <= withdrawals.length; i++) {
BimodalLib.Withdrawal storage withdrawal = withdrawals[withdrawals.length.sub(i)];
if (withdrawal.eon.add(1) < latestEon) {
break;
amounts[0] = amounts[0].add(withdrawal.amount);
amounts[1] = amounts[1].add(withdrawal.amount);
}
}
require(amounts[0].add(amounts[1]) > markerEonAvailable[1]);
if (amounts[1] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon, latestEon, amounts[1]);
ledger.appendOperationToEonAccumulator(
latestEon,
token,
withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[1]);
}
if (amounts[0] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon.sub(1), latestEon, amounts[0]);
ledger.appendOperationToEonAccumulator(
latestEon.sub(1),
token, withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[0]);
}
}
| 12,584,745 |
./partial_match/1/0x242b6973414Bc668C4537fBfd05986beAFdE6315/sources/ChainlinkOracle.sol
|
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.
|
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
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
);
}
| 4,415,823 |
./full_match/1/0x7049386F00BB8e1f7c41c8B7124b9DaF539Abc59/sources/contracts/ERC721/FairFellaz.sol
|
Override primary sale receiver/
|
function changePrimarySaleReceiver(
address newPrimarySaleReceiver
) external {
if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert UnauthorisedUser();
if (newPrimarySaleReceiver == address(0)) revert ZeroAddress();
_primarySaleReceiver = newPrimarySaleReceiver;
emit NewPrimarySaleReceiver(_primarySaleReceiver);
}
| 3,013,191 |
//sol Wallet
// Multi-sig, daily-limited account proxy/wallet.
// @authors:
// Gav Wood <[email protected]>
// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
contract multiowned {
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
}
// this contract only has two types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, hash operation);
// the other is in the case of an owner changing. here we record the old and new owners.
event OwnerChanged(address oldOwner, address newOwner);
// constructor is given number of sigs required to do protected "onlyowners" transactions
// as well as the selection of addresses capable of confirming them.
function multiowned(uint _required, address[] _owners) {
m_required = _required;
m_owners = _owners;
}
// simple single-sig function modifier.
modifier onlyowner {
if (m_owners.find(msg.sender) != notfound)
_
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(hash _operation) {
if (confirm(_operation))
_
}
function confirm(hash _operation) protected returns (bool _r) {
// determine what index the present sender is:
uint ownerIndex = m_owners.find(msg.sender);
// make sure they're an owner
if (ownerIndex != notfound) {
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (!m_pending[_operation].yetNeeded) {
// reset count of confirmations needed.
m_pending[_operation].yetNeeded = _sigs.size();
// reset which owners have confirmed (none) - set our bitmap to 0.
m_pending[_operation].ownersDone = 0;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 1 << ownerIndex;
// make sure we (the message sender) haven't confirmed this operation previously.
assert(m_pending[_operation].yetNeeded > 0);
if (!(m_pending[_operation].ownersDone & ownerIndexBit)) {
Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (m_pending[_operation].yetNeeded == 1) {
// enough confirmations: reset and run interior.
delete m_pending[_operation];
_r = true;
}
else
{
// not enough: record that this owner in particular confirmed.
m_pending[_operation].yetNeeded--;
m_pending[_operation].ownersDone |= ownerIndexBit;
}
}
}
}
// replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) external multiowned(sha3(msg.sig, _from, _to)) {
uint ownerIndex = m_owners.find(_from);
if (ownerIndex != notfound)
{
m_owners[ownerIndex] = _to;
OwnerChanged(_from, _to);
}
}
// the number of owners that must confirm the same operation before it is run.
uint constant m_required;
//stateset owners {
set address[] m_owners;
// set meaning you can do a fast look up into it to get the index.
// suggested impl as combination of count-prefixed contiguous series and normal mapping for the reverse lookup:
// sha3(BASE + 0) => N,
// sha3(BASE + 1) => address[0],
// ...
// sha3(BASE + N) => address[N-1],
// sha3(BASE ++ address[0]) => 1,
// ...
// sha3(BASE ++ address[N-1]) -> N
//
// provides:
// size: m_owners.size()
// dereference: m_owners[0], ..., m_owners[m_owners.size() - 1]
// alteration: m_owners[2] = newValue; (original m_owners[2] is removed)
// find: m_owners.find(m_owners[0]) == 0, ..., m_owners.find(m_owners[m_owners.size() - 1]) == m_owners.size() - 1, m_owners.find(...) == (uint)-1 == notfound
// append: m_owners.insert(n): m_owners[m_owners.size() - 1] == n, m_owners.lookup(n) == m_owners.size() - 1
// delete: delete m_owners[n]
// clear: m_owners.clear(): m_owners.size() == 0 (or just delete m_owners)
//}
/*
// for now could just be:
uint m_ownersCount;
mapping (uint => address) m_owners;
mapping (address => uint) m_ownersFind;
*/
// the ongoing operations.
mapping { hash => PendingState } m_pending;
}
// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
// uses is specified in the modifier.
contract daylimit is multiowned {
// constructor - just records the present day's index.
function daylimit() {
m_lastDay = today();
}
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
function setDailyLimit(uint _newLimit) external onlyowners(sha3(msg.sig, _newLimit)) {
m_dailyLimit = _newLimit;
}
// (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
function resetSpentToday() external onlyowners(sha3(msg.sig)) {
m_spentToday = 0;
}
// checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
// returns true. otherwise just returns false.
function underLimit(uint _value) protected onlyowner {
// reset the spend limit if we're on a different day to last time.
if (today() > m_lastDay) {
m_spentToday = 0;
m_lastDay = today();
}
// check to see if there's enough left - if so, subtract and return true.
if (m_spentToday + _value <= m_dailyLimit) {
m_spendToday += _value;
return true;
}
return false;
}
// simple modifier for daily limit.
modifier limitedDaily(uint _value) {
if (underLimit(_value))
_
}
// determines today's index.
function today() private constant returns (uint r) { r = block.timestamp / (60 * 60 * 24); }
uint m_spentToday;
uint m_dailyLimit;
uint m_lastDay;
}
// interface contract for multisig proxy contracts.
contract multisig {
function changeOwner(address _from, address _to) external;
function execute(address _to, uint _value, string _data) external returns (hash _r);
function confirm(hash _h) external;
}
// usage:
// hash h = Wallet(w).from(oneOwner).transact(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract Wallet is multisig multiowned daylimit {
// Transaction structure to remember details of transaction lest it need be saved for a later call.
structure Transaction {
address to;
uint value;
byte[] data;
}
// logged events:
// Funds has arrived into the wallet (record how much).
event CashIn(address indexed from, uint value);
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
event SingleTransact(string32 indexed out = "out", address owner, uint value, address to);
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
event MultiTransact(string32 indexed out = "out", address owner, hash operation, uint value, address to);
// constructor - just pass on the owner arra to the multiowned.
function Wallet(address[] _owners) multiowned(2, _owners) {}
// kills the contract sending everything to `_to`.
function kill(address _to) external onlyowners(sha3("kill", _to)) {
this.suicide(_to);
}
// gets called when no other function matches
function() {
// just being sent some cash?
if (msg.value) {
CashIn(msg.from, msg.value);
}
}
// Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function execute(address _to, uint _value, byte[] _data) external returns (hash _r) {
// first, take the opportunity to check that we're under the daily limit.
if (underLimit(_value)) {
log SingleTransact(_value, _to);
// yes - just execute the call.
_to.call(_value, _data);
return 0;
}
// determine our operation hash.
_r = sha3("transact", _to, _value, _data);
if (!confirm(_r) && m_txs[_r].to == 0) {
m_txs[_r].to = _to;
m_txs[_r].value = _value;
m_txs[_r].data = _data;
}
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirm(hash _h) external onlyowners(_h) {
if (m_txs[_h].to != 0) {
m_txs[_h].to.call(m_txs[_h].value, m_txs[_h].data);
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to);
delete m_txs[_h];
}
}
// internally confirm transaction with all of the info. returns true iff confirmed good and executed.
function confirm(hash _h, address _to, uint _value, bytes[] _data) private onlyowners(_h) returns (bool _r) {
_to.call(_value, _data);
MultiTransact(msg.sender, _h, _value, _to);
_r = true;
}
// pending transactions we have at present.
mapping (hash => Transaction) m_txs;
}
|
(re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
|
function resetSpentToday() external onlyowners(sha3(msg.sig)) {
m_spentToday = 0;
}
| 1,847,781 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BToken.sol";
import "./BMath.sol";
// Core contract; can't be changed. So disable solhint (reminder for v2)
/* solhint-disable func-order */
/* solhint-disable event-name-camelcase */
contract BPool is BBronze, BToken, BMath {
struct Record {
bool bound; // is token bound to pool
uint256 index; // private
uint256 denorm; // denormalized weight
uint256 balance;
}
event LOG_SWAP(
address indexed caller,
address indexed tokenIn,
address indexed tokenOut,
uint256 tokenAmountIn,
uint256 tokenAmountOut
);
event LOG_JOIN(address indexed caller, address indexed tokenIn, uint256 tokenAmountIn);
event LOG_EXIT(address indexed caller, address indexed tokenOut, uint256 tokenAmountOut);
event LOG_CALL(bytes4 indexed sig, address indexed caller, bytes data) anonymous;
modifier _logs_() {
emit LOG_CALL(msg.sig, msg.sender, msg.data);
_;
}
modifier _lock_() {
require(!_mutex, "ERR_REENTRY");
_mutex = true;
_;
_mutex = false;
}
modifier _viewlock_() {
require(!_mutex, "ERR_REENTRY");
_;
}
bool private _mutex;
address private _factory; // BFactory address to push token exitFee to
address private _controller; // has CONTROL role
bool private _publicSwap; // true if PUBLIC can call SWAP functions
// `setSwapFee` and `finalize` require CONTROL
// `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN`
uint256 private _swapFee;
bool private _finalized;
address[] private _tokens;
mapping(address => Record) private _records;
uint256 private _totalWeight;
bool public initialized;
constructor() public {
initialized = true;
}
function init() public {
require(initialized == false, "Pool already initialized");
_controller = msg.sender;
_factory = msg.sender;
_swapFee = MIN_FEE;
_publicSwap = false;
_finalized = false;
}
function isPublicSwap() external view returns (bool) {
return _publicSwap;
}
function isFinalized() external view returns (bool) {
return _finalized;
}
function isBound(address t) external view returns (bool) {
return _records[t].bound;
}
function getNumTokens() external view returns (uint256) {
return _tokens.length;
}
function getCurrentTokens() external view _viewlock_ returns (address[] memory tokens) {
return _tokens;
}
function getFinalTokens() external view _viewlock_ returns (address[] memory tokens) {
require(_finalized, "ERR_NOT_FINALIZED");
return _tokens;
}
function getDenormalizedWeight(address token) external view _viewlock_ returns (uint256) {
require(_records[token].bound, "ERR_NOT_BOUND");
return _records[token].denorm;
}
function getTotalDenormalizedWeight() external view _viewlock_ returns (uint256) {
return _totalWeight;
}
function getNormalizedWeight(address token) external view _viewlock_ returns (uint256) {
require(_records[token].bound, "ERR_NOT_BOUND");
uint256 denorm = _records[token].denorm;
return bdiv(denorm, _totalWeight);
}
function getBalance(address token) external view _viewlock_ returns (uint256) {
require(_records[token].bound, "ERR_NOT_BOUND");
return _records[token].balance;
}
function getSwapFee() external view _viewlock_ returns (uint256) {
return _swapFee;
}
function getController() external view _viewlock_ returns (address) {
return _controller;
}
function setSwapFee(uint256 swapFee) external _logs_ _lock_ {
require(!_finalized, "ERR_IS_FINALIZED");
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(swapFee >= MIN_FEE, "ERR_MIN_FEE");
require(swapFee <= MAX_FEE, "ERR_MAX_FEE");
_swapFee = swapFee;
}
function setController(address manager) external _logs_ _lock_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
_controller = manager;
}
function setPublicSwap(bool public_) external _logs_ _lock_ {
require(!_finalized, "ERR_IS_FINALIZED");
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
_publicSwap = public_;
}
function finalize() external _logs_ _lock_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(!_finalized, "ERR_IS_FINALIZED");
require(_tokens.length >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS");
_finalized = true;
_publicSwap = true;
_mintPoolShare(INIT_POOL_SUPPLY);
_pushPoolShare(msg.sender, INIT_POOL_SUPPLY);
}
function bind(
address token,
uint256 balance,
uint256 denorm
)
external
_logs_ // _lock_ Bind does not lock because it jumps to `rebind`, which does
{
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(!_records[token].bound, "ERR_IS_BOUND");
require(!_finalized, "ERR_IS_FINALIZED");
require(_tokens.length < MAX_BOUND_TOKENS, "ERR_MAX_TOKENS");
_records[token] = Record({
bound: true,
index: _tokens.length,
denorm: 0, // balance and denorm will be validated
balance: 0 // and set by `rebind`
});
_tokens.push(token);
rebind(token, balance, denorm);
}
function rebind(
address token,
uint256 balance,
uint256 denorm
) public _logs_ _lock_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(_records[token].bound, "ERR_NOT_BOUND");
require(!_finalized, "ERR_IS_FINALIZED");
require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT");
require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT");
require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE");
// Adjust the denorm and totalWeight
uint256 oldWeight = _records[token].denorm;
if (denorm > oldWeight) {
_totalWeight = badd(_totalWeight, bsub(denorm, oldWeight));
require(_totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT");
} else if (denorm < oldWeight) {
_totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm));
}
_records[token].denorm = denorm;
// Adjust the balance record and actual token balance
uint256 oldBalance = _records[token].balance;
_records[token].balance = balance;
if (balance > oldBalance) {
_pullUnderlying(token, msg.sender, bsub(balance, oldBalance));
} else if (balance < oldBalance) {
// In this case liquidity is being withdrawn, so charge EXIT_FEE
uint256 tokenBalanceWithdrawn = bsub(oldBalance, balance);
uint256 tokenExitFee = bmul(tokenBalanceWithdrawn, EXIT_FEE);
_pushUnderlying(token, msg.sender, bsub(tokenBalanceWithdrawn, tokenExitFee));
_pushUnderlying(token, _factory, tokenExitFee);
}
}
function unbind(address token) external _logs_ _lock_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(_records[token].bound, "ERR_NOT_BOUND");
require(!_finalized, "ERR_IS_FINALIZED");
uint256 tokenBalance = _records[token].balance;
uint256 tokenExitFee = bmul(tokenBalance, EXIT_FEE);
_totalWeight = bsub(_totalWeight, _records[token].denorm);
// Swap the token-to-unbind with the last token,
// then delete the last token
uint256 index = _records[token].index;
uint256 last = _tokens.length - 1;
_tokens[index] = _tokens[last];
_records[_tokens[index]].index = index;
_tokens.pop();
_records[token] = Record({bound: false, index: 0, denorm: 0, balance: 0});
_pushUnderlying(token, msg.sender, bsub(tokenBalance, tokenExitFee));
_pushUnderlying(token, _factory, tokenExitFee);
}
// Absorb any tokens that have been sent to this contract into the pool
function gulp(address token) external _logs_ _lock_ {
require(_records[token].bound, "ERR_NOT_BOUND");
_records[token].balance = IERC20(token).balanceOf(address(this));
}
function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint256 spotPrice) {
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
Record storage inRecord = _records[tokenIn];
Record storage outRecord = _records[tokenOut];
return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee);
}
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external
view
_viewlock_
returns (uint256 spotPrice)
{
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
Record storage inRecord = _records[tokenIn];
Record storage outRecord = _records[tokenOut];
return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, 0);
}
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external _logs_ _lock_ {
require(_finalized, "ERR_NOT_FINALIZED");
uint256 poolTotal = totalSupply();
uint256 ratio = bdiv(poolAmountOut, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
for (uint256 i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint256 bal = _records[t].balance;
uint256 tokenAmountIn = bmul(ratio, bal);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN");
_records[t].balance = badd(_records[t].balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, t, tokenAmountIn);
_pullUnderlying(t, msg.sender, tokenAmountIn);
}
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
}
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external _logs_ _lock_ {
require(_finalized, "ERR_NOT_FINALIZED");
uint256 poolTotal = totalSupply();
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee);
uint256 ratio = bdiv(pAiAfterExitFee, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
_pullPoolShare(msg.sender, poolAmountIn);
_pushPoolShare(_factory, exitFee);
_burnPoolShare(pAiAfterExitFee);
for (uint256 i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint256 bal = _records[t].balance;
uint256 tokenAmountOut = bmul(ratio, bal);
require(tokenAmountOut != 0, "ERR_MATH_APPROX");
require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT");
_records[t].balance = bsub(_records[t].balance, tokenAmountOut);
emit LOG_EXIT(msg.sender, t, tokenAmountOut);
_pushUnderlying(t, msg.sender, tokenAmountOut);
}
}
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external _logs_ _lock_ returns (uint256 tokenAmountOut, uint256 spotPriceAfter) {
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
require(_publicSwap, "ERR_SWAP_NOT_PUBLIC");
Record storage inRecord = _records[address(tokenIn)];
Record storage outRecord = _records[address(tokenOut)];
require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO");
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
tokenAmountOut = calcOutGivenIn(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX");
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return (tokenAmountOut, spotPriceAfter);
}
function swapExactAmountOut(
address tokenIn,
uint256 maxAmountIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPrice
) external _logs_ _lock_ returns (uint256 tokenAmountIn, uint256 spotPriceAfter) {
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
require(_publicSwap, "ERR_SWAP_NOT_PUBLIC");
Record storage inRecord = _records[address(tokenIn)];
Record storage outRecord = _records[address(tokenOut)];
require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO");
uint256 spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
tokenAmountIn = calcInGivenOut(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountOut,
_swapFee
);
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX");
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return (tokenAmountIn, spotPriceAfter);
}
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut
) external _logs_ _lock_ returns (uint256 poolAmountOut) {
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO");
Record storage inRecord = _records[tokenIn];
poolAmountOut = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn,
_swapFee
);
require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return poolAmountOut;
}
function joinswapPoolAmountOut(
address tokenIn,
uint256 poolAmountOut,
uint256 maxAmountIn
) external _logs_ _lock_ returns (uint256 tokenAmountIn) {
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
Record storage inRecord = _records[tokenIn];
tokenAmountIn = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut,
_swapFee
);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return tokenAmountIn;
}
function exitswapPoolAmountIn(
address tokenOut,
uint256 poolAmountIn,
uint256 minAmountOut
) external _logs_ _lock_ returns (uint256 tokenAmountOut) {
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
Record storage outRecord = _records[tokenOut];
tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO");
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_factory, exitFee);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return tokenAmountOut;
}
function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
) external _logs_ _lock_ returns (uint256 poolAmountIn) {
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO");
Record storage outRecord = _records[tokenOut];
poolAmountIn = calcPoolInGivenSingleOut(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountOut,
_swapFee
);
require(poolAmountIn != 0, "ERR_MATH_APPROX");
require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN");
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
uint256 exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_factory, exitFee);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return poolAmountIn;
}
// ==
// 'Underlying' token-manipulation functions make external calls but are NOT locked
// You must `_lock_` or otherwise ensure reentry-safety
function _pullUnderlying(
address erc20,
address from,
uint256 amount
) internal {
bool xfer = IERC20(erc20).transferFrom(from, address(this), amount);
require(xfer, "ERR_ERC20_FALSE");
}
function _pushUnderlying(
address erc20,
address to,
uint256 amount
) internal {
bool xfer = IERC20(erc20).transfer(to, amount);
require(xfer, "ERR_ERC20_FALSE");
}
function _pullPoolShare(address from, uint256 amount) internal {
_pull(from, amount);
}
function _pushPoolShare(address to, uint256 amount) internal {
_push(to, amount);
}
function _mintPoolShare(uint256 amount) internal {
_mint(amount);
}
function _burnPoolShare(uint256 amount) internal {
_burn(amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BNum.sol";
import "./PCToken.sol";
// Highly opinionated token implementation
/*
interface IERC20 {
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
}
*/
// Core contract; can't be changed. So disable solhint (reminder for v2)
/* solhint-disable func-order */
contract BTokenBase is BNum {
mapping(address => uint256) internal _balance;
mapping(address => mapping(address => uint256)) internal _allowance;
uint256 internal _totalSupply;
event Approval(address indexed src, address indexed dst, uint256 amt);
event Transfer(address indexed src, address indexed dst, uint256 amt);
function _mint(uint256 amt) internal {
_balance[address(this)] = badd(_balance[address(this)], amt);
_totalSupply = badd(_totalSupply, amt);
emit Transfer(address(0), address(this), amt);
}
function _burn(uint256 amt) internal {
require(_balance[address(this)] >= amt, "ERR_INSUFFICIENT_BAL");
_balance[address(this)] = bsub(_balance[address(this)], amt);
_totalSupply = bsub(_totalSupply, amt);
emit Transfer(address(this), address(0), amt);
}
function _move(
address src,
address dst,
uint256 amt
) internal {
require(_balance[src] >= amt, "ERR_INSUFFICIENT_BAL");
_balance[src] = bsub(_balance[src], amt);
_balance[dst] = badd(_balance[dst], amt);
emit Transfer(src, dst, amt);
}
function _push(address to, uint256 amt) internal {
_move(address(this), to, amt);
}
function _pull(address from, uint256 amt) internal {
_move(from, address(this), amt);
}
}
contract BToken is BTokenBase, IERC20 {
string private _name = "Balancer Pool Token";
string private _symbol = "BPT";
uint8 private _decimals = 18;
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function allowance(address src, address dst) external view override returns (uint256) {
return _allowance[src][dst];
}
function balanceOf(address whom) external view override returns (uint256) {
return _balance[whom];
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function approve(address dst, uint256 amt) external override returns (bool) {
_allowance[msg.sender][dst] = amt;
emit Approval(msg.sender, dst, amt);
return true;
}
function increaseApproval(address dst, uint256 amt) external returns (bool) {
_allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt);
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function decreaseApproval(address dst, uint256 amt) external returns (bool) {
uint256 oldValue = _allowance[msg.sender][dst];
if (amt > oldValue) {
_allowance[msg.sender][dst] = 0;
} else {
_allowance[msg.sender][dst] = bsub(oldValue, amt);
}
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function transfer(address dst, uint256 amt) external override returns (bool) {
_move(msg.sender, dst, amt);
return true;
}
function transferFrom(
address src,
address dst,
uint256 amt
) external override returns (bool) {
require(msg.sender == src || amt <= _allowance[src][msg.sender], "ERR_BTOKEN_BAD_CALLER");
_move(src, dst, amt);
if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) {
_allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt);
emit Approval(msg.sender, dst, _allowance[src][msg.sender]);
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BNum.sol";
contract BMath is BBronze, BConst, BNum {
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcSpotPrice(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 swapFee
) public pure returns (uint256 spotPrice) {
uint256 numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint256 denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint256 ratio = bdiv(numer, denom);
uint256 scale = bdiv(BONE, bsub(BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcOutGivenIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountIn,
uint256 swapFee
) public pure returns (uint256 tokenAmountOut) {
uint256 weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint256 adjustedIn = bsub(BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint256 y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
uint256 foo = bpow(y, weightRatio);
uint256 bar = bsub(BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
return tokenAmountOut;
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee //
**********************************************************************************************/
function calcInGivenOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountOut,
uint256 swapFee
) public pure returns (uint256 tokenAmountIn) {
uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint256 diff = bsub(tokenBalanceOut, tokenAmountOut);
uint256 y = bdiv(tokenBalanceOut, diff);
uint256 foo = bpow(y, weightRatio);
foo = bsub(foo, BONE);
tokenAmountIn = bsub(BONE, swapFee);
tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);
return tokenAmountIn;
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee \ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) public pure returns (uint256 poolAmountOut) {
// Charge the trading fee for the proportion of tokenAi
// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
uint256 tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));
uint256 newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint256 tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint256 poolRatio = bpow(tokenInRatio, normalizedWeight);
uint256 newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return poolAmountOut;
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) public pure returns (uint256 tokenAmountIn) {
uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint256 newPoolSupply = badd(poolSupply, poolAmountOut);
uint256 poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint256 boo = bdiv(BONE, normalizedWeight);
uint256 tokenInRatio = bpow(poolRatio, boo);
uint256 newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint256 tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint256 zar = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) public pure returns (uint256 tokenAmountOut) {
uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight);
// charge exit fee on the pool token side
// pAiAfterExitFee = pAi*(1-exitFee)
uint256 poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE));
uint256 newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);
uint256 poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint256 tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));
uint256 newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint256 tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight ------------------------------------------------------------- //
// sF = swapFee ( 1 - eF ) //
// eF = exitFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) public pure returns (uint256 poolAmountIn) {
// charge swap fee on the output token side
uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight);
//uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;
uint256 zoo = bsub(BONE, normalizedWeight);
uint256 zar = bmul(zoo, swapFee);
uint256 tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar));
uint256 newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee);
uint256 tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint256 poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint256 newPoolSupply = bmul(poolRatio, poolSupply);
uint256 poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE));
return poolAmountIn;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BConst.sol";
// Core contract; can't be changed. So disable solhint (reminder for v2)
/* solhint-disable private-vars-leading-underscore */
contract BNum is BConst {
function btoi(uint256 a) internal pure returns (uint256) {
return a / BONE;
}
function bfloor(uint256 a) internal pure returns (uint256) {
return btoi(a) * BONE;
}
function badd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) {
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint256 c2 = c1 / BONE;
return c2;
}
function bdiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint256 c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint256 a, uint256 n) internal pure returns (uint256) {
uint256 z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint256 base, uint256 exp) internal pure returns (uint256) {
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint256 whole = bfloor(exp);
uint256 remain = bsub(exp, whole);
uint256 wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(
uint256 base,
uint256 exp,
uint256 precision
) internal pure returns (uint256) {
// term 0:
uint256 a = exp;
(uint256 x, bool xneg) = bsubSign(base, BONE);
uint256 term = BONE;
uint256 sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BONE;
(uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
// Imports
import "./libraries/BalancerSafeMath.sol";
import "./interfaces/IERC20.sol";
// Contracts
/* solhint-disable func-order */
/**
* @author Balancer Labs
* @title Highly opinionated token implementation
*/
contract PCToken is IERC20 {
using BalancerSafeMath for uint256;
// State variables
string public constant NAME = "Balancer Smart Pool";
uint8 public constant DECIMALS = 18;
// No leading underscore per naming convention (non-private)
// Cannot call totalSupply (name conflict)
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal varTotalSupply;
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowance;
string private _symbol;
string private _name;
// Event declarations
// See definitions above; must be redeclared to be emitted from this contract
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
// Function declarations
/**
* @notice Base token constructor
* @param tokenSymbol - the token symbol
*/
constructor(string memory tokenSymbol, string memory tokenName) public {
_symbol = tokenSymbol;
_name = tokenName;
}
// External functions
/**
* @notice Getter for allowance: amount spender will be allowed to spend on behalf of owner
* @param owner - owner of the tokens
* @param spender - entity allowed to spend the tokens
* @return uint - remaining amount spender is allowed to transfer
*/
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowance[owner][spender];
}
/**
* @notice Getter for current account balance
* @param account - address we're checking the balance of
* @return uint - token balance in the account
*/
function balanceOf(address account) external view override returns (uint256) {
return _balance[account];
}
/**
* @notice Approve owner (sender) to spend a certain amount
* @dev emits an Approval event
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function approve(address spender, uint256 amount) external override returns (bool) {
/* In addition to the increase/decreaseApproval functions, could
avoid the "approval race condition" by only allowing calls to approve
when the current approval amount is 0
require(_allowance[msg.sender][spender] == 0, "ERR_RACE_CONDITION");
Some token contracts (e.g., KNC), already revert if you call approve
on a non-zero allocation. To deal with these, we use the SafeApprove library
and safeApprove function when adding tokens to the pool.
*/
_allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Increase the amount the spender is allowed to spend on behalf of the owner (sender)
* @dev emits an Approval event
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function increaseApproval(address spender, uint256 amount) external returns (bool) {
_allowance[msg.sender][spender] = BalancerSafeMath.badd(_allowance[msg.sender][spender], amount);
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @notice Decrease the amount the spender is allowed to spend on behalf of the owner (sender)
* @dev emits an Approval event
* @dev If you try to decrease it below the current limit, it's just set to zero (not an error)
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function decreaseApproval(address spender, uint256 amount) external returns (bool) {
uint256 oldValue = _allowance[msg.sender][spender];
// Gas optimization - if amount == oldValue (or is larger), set to zero immediately
if (amount >= oldValue) {
_allowance[msg.sender][spender] = 0;
} else {
_allowance[msg.sender][spender] = BalancerSafeMath.bsub(oldValue, amount);
}
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @notice Transfer the given amount from sender (caller) to recipient
* @dev _move emits a Transfer event if successful
* @param recipient - entity receiving the tokens
* @param amount - number of tokens being transferred
* @return bool - result of the transfer (will always be true if it doesn't revert)
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
require(recipient != address(0), "ERR_ZERO_ADDRESS");
_move(msg.sender, recipient, amount);
return true;
}
/**
* @notice Transfer the given amount from sender to recipient
* @dev _move emits a Transfer event if successful; may also emit an Approval event
* @param sender - entity sending the tokens (must be caller or allowed to spend on behalf of caller)
* @param recipient - recipient of the tokens
* @param amount - number of tokens being transferred
* @return bool - result of the transfer (will always be true if it doesn't revert)
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
require(recipient != address(0), "ERR_ZERO_ADDRESS");
require(msg.sender == sender || amount <= _allowance[sender][msg.sender], "ERR_PCTOKEN_BAD_CALLER");
_move(sender, recipient, amount);
// memoize for gas optimization
uint256 oldAllowance = _allowance[sender][msg.sender];
// If the sender is not the caller, adjust the allowance by the amount transferred
if (msg.sender != sender && oldAllowance != uint256(-1)) {
_allowance[sender][msg.sender] = BalancerSafeMath.bsub(oldAllowance, amount);
emit Approval(msg.sender, recipient, _allowance[sender][msg.sender]);
}
return true;
}
// public functions
/**
* @notice Getter for the total supply
* @dev declared external for gas optimization
* @return uint - total number of tokens in existence
*/
function totalSupply() external view override returns (uint256) {
return varTotalSupply;
}
// Public functions
/**
* @dev Returns the name of the token.
* We allow the user to set this name (as well as the symbol).
* Alternatives are 1) A fixed string (original design)
* 2) A fixed string plus the user-defined symbol
* return string(abi.encodePacked(NAME, "-", _symbol));
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external pure returns (uint8) {
return DECIMALS;
}
// internal functions
// Mint an amount of new tokens, and add them to the balance (and total supply)
// Emit a transfer amount from the null address to this contract
function _mint(uint256 amount) internal virtual {
_balance[address(this)] = BalancerSafeMath.badd(_balance[address(this)], amount);
varTotalSupply = BalancerSafeMath.badd(varTotalSupply, amount);
emit Transfer(address(0), address(this), amount);
}
// Burn an amount of new tokens, and subtract them from the balance (and total supply)
// Emit a transfer amount from this contract to the null address
function _burn(uint256 amount) internal virtual {
// Can't burn more than we have
// Remove require for gas optimization - bsub will revert on underflow
// require(_balance[address(this)] >= amount, "ERR_INSUFFICIENT_BAL");
_balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount);
varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount);
emit Transfer(address(this), address(0), amount);
}
// Transfer tokens from sender to recipient
// Adjust balances, and emit a Transfer event
function _move(
address sender,
address recipient,
uint256 amount
) internal virtual {
// Can't send more than sender has
// Remove require for gas optimization - bsub will revert on underflow
// require(_balance[sender] >= amount, "ERR_INSUFFICIENT_BAL");
_balance[sender] = BalancerSafeMath.bsub(_balance[sender], amount);
_balance[recipient] = BalancerSafeMath.badd(_balance[recipient], amount);
emit Transfer(sender, recipient, amount);
}
// Transfer from this contract to recipient
// Emits a transfer event if successful
function _push(address recipient, uint256 amount) internal {
_move(address(this), recipient, amount);
}
// Transfer from recipient to this contract
// Emits a transfer event if successful
function _pull(address sender, uint256 amount) internal {
_move(sender, address(this), amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BColor.sol";
contract BConst is BBronze {
uint256 public constant BONE = 10**18;
uint256 public constant MIN_BOUND_TOKENS = 2;
uint256 public constant MAX_BOUND_TOKENS = 8;
uint256 public constant MIN_FEE = BONE / 10**6;
uint256 public constant MAX_FEE = BONE / 10;
uint256 public constant EXIT_FEE = 0;
uint256 public constant MIN_WEIGHT = BONE;
uint256 public constant MAX_WEIGHT = BONE * 50;
uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint256 public constant MIN_BALANCE = BONE / 10**12;
uint256 public constant INIT_POOL_SUPPLY = BONE * 100;
uint256 public constant MIN_BPOW_BASE = 1 wei;
uint256 public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint256 public constant BPOW_PRECISION = BONE / 10**10;
uint256 public constant MAX_IN_RATIO = BONE / 2;
uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
// abstract contract BColor {
// function getColor()
// external view virtual
// returns (bytes32);
// }
contract BBronze {
function getColor() external pure returns (bytes32) {
return bytes32("BRONZE");
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
// Imports
import "./BalancerConstants.sol";
/**
* @author Balancer Labs
* @title SafeMath - wrap Solidity operators to prevent underflow/overflow
* @dev badd and bsub are basically identical to OpenZeppelin SafeMath; mul/div have extra checks
*/
library BalancerSafeMath {
/**
* @notice Safe addition
* @param a - first operand
* @param b - second operand
* @dev if we are adding b to a, the resulting sum must be greater than a
* @return - sum of operands; throws if overflow
*/
function badd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
/**
* @notice Safe unsigned subtraction
* @param a - first operand
* @param b - second operand
* @dev Do a signed subtraction, and check that it produces a positive value
* (i.e., a - b is valid if b <= a)
* @return - a - b; throws if underflow
*/
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool negativeResult) = bsubSign(a, b);
require(!negativeResult, "ERR_SUB_UNDERFLOW");
return c;
}
/**
* @notice Safe signed subtraction
* @param a - first operand
* @param b - second operand
* @dev Do a signed subtraction
* @return - difference between a and b, and a flag indicating a negative result
* (i.e., a - b if a is greater than or equal to b; otherwise b - a)
*/
function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) {
if (b <= a) {
return (a - b, false);
} else {
return (b - a, true);
}
}
/**
* @notice Safe multiplication
* @param a - first operand
* @param b - second operand
* @dev Multiply safely (and efficiently), rounding down
* @return - product of operands; throws if overflow or rounding error
*/
function bmul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization (see github.com/OpenZeppelin/openzeppelin-contracts/pull/522)
if (a == 0) {
return 0;
}
// Standard overflow check: a/a*b=b
uint256 c0 = a * b;
require(c0 / a == b, "ERR_MUL_OVERFLOW");
// Round to 0 if x*y < BONE/2?
uint256 c1 = c0 + (BalancerConstants.BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint256 c2 = c1 / BalancerConstants.BONE;
return c2;
}
/**
* @notice Safe division
* @param dividend - first operand
* @param divisor - second operand
* @dev Divide safely (and efficiently), rounding down
* @return - quotient; throws if overflow or rounding error
*/
function bdiv(uint256 dividend, uint256 divisor) internal pure returns (uint256) {
require(divisor != 0, "ERR_DIV_ZERO");
// Gas optimization
if (dividend == 0) {
return 0;
}
uint256 c0 = dividend * BalancerConstants.BONE;
require(c0 / dividend == BalancerConstants.BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint256 c1 = c0 + (divisor / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint256 c2 = c1 / divisor;
return c2;
}
/**
* @notice Safe unsigned integer modulo
* @dev Returns the remainder of dividing two unsigned integers.
* 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).
*
* @param dividend - first operand
* @param divisor - second operand -- cannot be zero
* @return - quotient; throws if overflow or rounding error
*/
function bmod(uint256 dividend, uint256 divisor) internal pure returns (uint256) {
require(divisor != 0, "ERR_MODULO_BY_ZERO");
return dividend % divisor;
}
/**
* @notice Safe unsigned integer max
* @dev Returns the greater of the two input values
*
* @param a - first operand
* @param b - second operand
* @return - the maximum of a and b
*/
function bmax(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @notice Safe unsigned integer min
* @dev returns b, if b < a; otherwise returns a
*
* @param a - first operand
* @param b - second operand
* @return - the lesser of the two input values
*/
function bmin(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @notice Safe unsigned integer average
* @dev Guard against (a+b) overflow by dividing each operand separately
*
* @param a - first operand
* @param b - second operand
* @return - the average of the two values
*/
function baverage(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
/**
* @notice Babylonian square root implementation
* @dev (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
* @param y - operand
* @return z - the square root result
*/
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;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
// Interface declarations
/* solhint-disable func-order */
interface IERC20 {
// 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);
// 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);
// Returns the amount of tokens in existence
function totalSupply() external view returns (uint256);
// Returns the amount of tokens owned by account
function balanceOf(address account) external view returns (uint256);
// 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);
// Sets amount as the allowance of spender over the caller’s tokens
// Returns a boolean value indicating whether the operation succeeded
// Emits an Approval event.
function approve(address spender, uint256 amount) external returns (bool);
// 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);
// 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);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
/**
* @author Balancer Labs
* @title Put all the constants in one place
*/
library BalancerConstants {
// State variables (must be constant in a library)
// B "ONE" - all math is in the "realm" of 10 ** 18;
// where numeric 1 = 10 ** 18
uint256 public constant BONE = 10**18;
uint256 public constant MIN_WEIGHT = BONE;
uint256 public constant MAX_WEIGHT = BONE * 50;
uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint256 public constant MIN_BALANCE = BONE / 10**6;
uint256 public constant MAX_BALANCE = BONE * 10**12;
uint256 public constant MIN_POOL_SUPPLY = BONE * 100;
uint256 public constant MAX_POOL_SUPPLY = BONE * 10**9;
uint256 public constant MIN_FEE = BONE / 10**6;
uint256 public constant MAX_FEE = BONE / 10;
// EXIT_FEE must always be zero, or ConfigurableRightsPool._pushUnderlying will fail
uint256 public constant EXIT_FEE = 0;
uint256 public constant MAX_IN_RATIO = BONE / 2;
uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
// Must match BConst.MIN_BOUND_TOKENS and BConst.MAX_BOUND_TOKENS
uint256 public constant MIN_ASSET_LIMIT = 2;
uint256 public constant MAX_ASSET_LIMIT = 8;
uint256 public constant MAX_UINT = uint256(-1);
}
|
Burn an amount of new tokens, and subtract them from the balance (and total supply) Emit a transfer amount from this contract to the null address Can't burn more than we have Remove require for gas optimization - bsub will revert on underflow require(_balance[address(this)] >= amount, "ERR_INSUFFICIENT_BAL");
|
function _burn(uint256 amount) internal virtual {
_balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount);
varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount);
emit Transfer(address(this), address(0), amount);
}
| 303,197 |
./full_match/4/0x87f0D1e1AC129f5a2B8995d21E8B6ff3D42Fd896/sources/browser/BaoMasterFarmer_flat.sol
|
Update Reward Per Block
|
function rewardUpdate(uint256 _newReward) public onlyAuthorized {
REWARD_PER_BLOCK = _newReward;
}
| 746,850 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint32 _value, address _token, bytes _extraData) public; }
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// 實現所有權轉移
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract x32323 is owned {
function TokenERC20(
uint32 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
address centralMinter
) {
if(centralMinter != 0 ) owner = centralMinter;
}
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 0;
// 18 decimals is the strongly suggested default, avoid changing it
uint32 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, uint32 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint32 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint32 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = 23000000 ; // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "測試"; // Set the name for display purposes
symbol = "測試"; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function _transfer(address _from, address _to, uint32 _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to , _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint32 _value) public {
require(!frozenAccount[msg.sender]);
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint32 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint32 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint32 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint32 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint32 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
|
Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough Check for overflows Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
|
function _transfer(address _from, address _to, uint32 _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to , _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
| 10,776,833 |
./partial_match/3/0x50fef2Bb63b907Fa3897B8F35bd0F318E65478FB/sources/NexaBook.sol
|
8X /set current level
|
function updateX8Referrer(address userAddress, address referrerAddress, uint8 level, uint noOfTokens) private {
require(users[referrerAddress].activeX8Levels[level], "500. Referrer level is inactive");
if (users[referrerAddress].x8Matrix[level].firstLevelReferrals.length < 2) {
users[referrerAddress].x8Matrix[level].firstLevelReferrals.push(userAddress);
emit NewUserPlace(userAddress, referrerAddress, 3, level, uint8(users[referrerAddress].x8Matrix[level].firstLevelReferrals.length));
users[userAddress].x8Matrix[level].currentReferrer = referrerAddress;
if (referrerAddress == owner) {
return sendETHDividends(referrerAddress, userAddress, 3, level, noOfTokens);
}
address ref = users[referrerAddress].x8Matrix[level].currentReferrer;
users[ref].x8Matrix[level].secondLevelReferrals.push(userAddress);
address ref1 = users[ref].x8Matrix[level].currentReferrer;
users[ref1].x8Matrix[level].thirdlevelreferrals.push(userAddress);
uint len = users[ref].x8Matrix[level].firstLevelReferrals.length;
uint8 toppos=2;
if(ref1!=address(0x0)){
if(ref==users[ref1].x8Matrix[level].firstLevelReferrals[0]){
toppos=1;
}else
{
toppos=2;
}
}
if ((len == 2) &&
(users[ref].x8Matrix[level].firstLevelReferrals[0] == referrerAddress) &&
(users[ref].x8Matrix[level].firstLevelReferrals[1] == referrerAddress)) {
if (users[referrerAddress].x8Matrix[level].firstLevelReferrals.length == 1) {
users[ref].x8Matrix[level].place.push(5);
emit NewUserPlace(userAddress, ref, 3, level, 5);
emit NewUserPlace(userAddress, ref1, 3, level, (4*toppos)+5);
users[ref].x8Matrix[level].place.push(6);
emit NewUserPlace(userAddress, ref, 3, level, 6);
emit NewUserPlace(userAddress, ref1, 3, level, (4*toppos)+5);
}
} else
if ((len == 1 || len == 2) &&
users[ref].x8Matrix[level].firstLevelReferrals[0] == referrerAddress) {
if (users[referrerAddress].x8Matrix[level].firstLevelReferrals.length == 1) {
users[ref].x8Matrix[level].place.push(3);
emit NewUserPlace(userAddress, ref, 3, level, 3);
emit NewUserPlace(userAddress, ref1, 3, level, (4*toppos)+3);
users[ref].x8Matrix[level].place.push(4);
emit NewUserPlace(userAddress, ref, 3, level, 4);
emit NewUserPlace(userAddress, ref1, 3, level, (4*toppos)+4);
}
if (users[referrerAddress].x8Matrix[level].firstLevelReferrals.length == 1) {
users[ref].x8Matrix[level].place.push(5);
emit NewUserPlace(userAddress, ref, 3, level, 5);
emit NewUserPlace(userAddress, ref1, 3, level, (4*toppos)+5);
users[ref].x8Matrix[level].place.push(6);
emit NewUserPlace(userAddress, ref, 3, level, 6);
emit NewUserPlace(userAddress, ref1, 3, level, (4*toppos)+6);
}
}
return updateX8ReferrerSecondLevel(userAddress, ref1, level, noOfTokens);
}
if (users[referrerAddress].x8Matrix[level].secondLevelReferrals.length < 4) {
users[referrerAddress].x8Matrix[level].secondLevelReferrals.push(userAddress);
address secondref = users[referrerAddress].x8Matrix[level].currentReferrer;
if(secondref==address(0x0))
secondref=owner;
if (users[referrerAddress].x8Matrix[level].firstLevelReferrals[1] == userAddress) {
updateX8(userAddress, referrerAddress, level, false);
return updateX8ReferrerSecondLevel(userAddress, secondref, level, noOfTokens);
updateX8(userAddress, referrerAddress, level, true);
return updateX8ReferrerSecondLevel(userAddress, secondref, level, noOfTokens);
}
if (users[users[referrerAddress].x8Matrix[level].firstLevelReferrals[0]].x8Matrix[level].firstLevelReferrals.length <
2) {
updateX8(userAddress, referrerAddress, level, false);
updateX8(userAddress, referrerAddress, level, true);
}
updateX8ReferrerSecondLevel(userAddress, secondref, level, noOfTokens);
}
else if (users[referrerAddress].x8Matrix[level].thirdlevelreferrals.length < 8) {
users[referrerAddress].x8Matrix[level].thirdlevelreferrals.push(userAddress);
if (users[users[referrerAddress].x8Matrix[level].secondLevelReferrals[0]].x8Matrix[level].firstLevelReferrals.length<2) {
updateX8Fromsecond(userAddress, referrerAddress, level, 0);
return updateX8ReferrerSecondLevel(userAddress, referrerAddress, level, noOfTokens);
updateX8Fromsecond(userAddress, referrerAddress, level, 1);
return updateX8ReferrerSecondLevel(userAddress, referrerAddress, level, noOfTokens);
updateX8Fromsecond(userAddress, referrerAddress, level, 2);
return updateX8ReferrerSecondLevel(userAddress, referrerAddress, level, noOfTokens);
updateX8Fromsecond(userAddress, referrerAddress, level, 3);
return updateX8ReferrerSecondLevel(userAddress, referrerAddress, level, noOfTokens);
}
updateX8ReferrerSecondLevel(userAddress, referrerAddress, level, noOfTokens);
}
}
| 5,092,705 |
./partial_match/1/0x0c9796fD8B4645358ee23Fb7920F9d4e617a524d/sources/OneCoinToken.sol
|
Burn tokens from address token holder address amount uint256 amount of tokens to burn data bytes extra information provided by the token holder operatorData bytes extra information provided by the operator (if any)/ Update state variables
|
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = msg.sender;
_beforeTokenTransfer(operator, from, address(0), amount);
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
| 2,609,995 |
./partial_match/1/0x891696CCa87aa2f175124b412198c23D54680E31/sources/NFTWinner.sol
|
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) public virtual override {
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
| 3,585,518 |
./partial_match/80001/0xEd494b640222d33F22a9156725d2a12a589fa3E0/sources/src/consensys_erc1400/ERC1400.sol
|
Get partitions index of a tokenholder. tokenHolder Address for which the partitions index are returned. return Array of partitions index of 'tokenHolder'./
|
function partitionsOf(address tokenHolder)
external
view
override
returns (bytes32[] memory)
{
return _partitionsOf[tokenHolder];
}
| 8,796,125 |
./full_match/41/0xED231ad1C1C88Db553Ac8d0C57028C01B792fEF7/sources/contracts/FarmBooster.sol
|
Anyone can call this function, if some users effective multiplier is not fair for other users, just call the 'refresh' function. _user user address. _pid pool id(MasterchefV2 pool). If return value not in range [BOOST_PRECISION, MAX_BOOST_PRECISION] the actual effective multiplier will be the closest to the side boundry value.
|
function getUserMultiplier(address _user, uint256 _pid) external view returns (uint256) {
return _boostCalculate(_user, proxyContract[_user], _pid, avgLockDuration());
}
| 16,371,295 |
/// base.sol -- basic ERC20 implementation
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.4.23;
import "erc20.sol";
import "math.sol";
contract TokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() external view returns (uint) {
return _supply;
}
function balanceOf(address src) external view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) external view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) external returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //Revert if funds insufficient.
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) external returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
event Mint(address guy, uint wad);
event Burn(address guy, uint wad);
function mint(uint wad) internal { //Note: _supply constant
_balances[msg.sender] = add(_balances[msg.sender], wad);
emit Mint(msg.sender, wad);
}
function burn(uint wad) internal { //Note: _supply constant
_balances[msg.sender] = sub(_balances[msg.sender], wad); //Revert if funds insufficient.
emit Burn(msg.sender, wad);
}
}
// Copyright (C) 2020 Benjamin M J D Wang
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.0;
import "gov_interface_v2.sol"; //Import governance contract interface.
import "proposal_tokens_v3.sol"; //proposal tokens data structure and transfer functions.
contract onchain_gov_BMJDW2020 is IOnchain_gov, proposal_tokens, onchain_gov_events{
ERC20 public ERC20Interface;
function calculate_price(uint _side, uint _now) public view returns (uint p) { //Function could also be internal if users can calculate price themselves easily.
uint[4] memory price_data = proposal[pa_proposal_id].next_init_price_data;
p = wmul(price_data[_side], wpow(price_data[2], mul(price_data[3], sub(_now, current_tranche_start))/WAD)); //(WAD)
//p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD));
/**
p = WAD
p1 = WAD
e = WAD
f = int
now = int
start = int
*/
}
function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external {
uint param = wdiv(_amount, mul(_next_min_prop_period, _prop_period)); //_next_min_prop_period is purely an anti-spam prevention to stop spammers submitting proposals with very small amounts. Assume WAD since _next_min_prop_period * _prop_period may result in large number.
require(param > top_param, "param < top_param");
require(_prop_period > proposal[pa_proposal_id].next_min_prop_period, "prop_period < minimum"); //check that voting period is greater than the next_min_prop_period of the last accepted proposal.
top_param = param; //Sets current top param to that of the resently submitted proposal.
ERC20Interface.transferFrom(msg.sender, address(this), _amount / 100);//Takes proposer's deposit in dai. This must throw an error and revert if the user does not have enough funds available.
ERC20Interface.transfer(proposal[top_proposal_id].beneficiary, proposal[top_proposal_id].amount / 100); ////Pays back the deposit to the old top proposer in dai.
uint id = ++nonce; //Implicit conversion to uint256
top_proposal_id = uint40(id); //set top proposal id and is used as id for recording data.
//Store all new proposal data:
proposal[id].beneficiary = msg.sender;
proposal[id].amount = _amount;
proposal[id].next_init_tranche_size = _next_init_tranche_size;
proposal[id].next_init_price_data = _next_init_price_data;
proposal[id].next_reject_spread_threshold = _next_reject_spread_threshold;
proposal[id].next_minimum_sell_volume = _next_minimum_sell_volume;
proposal[id].prop_period = _prop_period;
proposal[id].next_min_prop_period = _next_min_prop_period;
proposal[id].reset_time_period = _reset_time_period;
emit NewSubmission(uint40(id), msg.sender, _amount, _next_init_tranche_size, _next_init_price_data, _next_reject_spread_threshold, _next_minimum_sell_volume, _prop_period, _next_min_prop_period, _reset_time_period);
}
function init_proposal(uint40 _id) external { //'sell' and 'buy' indicate sell and buy side from the user perspective in the context of governance tokens even though it is in reference to dai.
require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished.
/**
When proposal has ended and was accepted:
pa_proposal_id = running_proposal_id
running_proposal_id = 0
When proposal has ended and was rejected:
pa_proposal_id remains the same.
running_proposal_id = 0
When initialised:
running_proposal_id = top_proposal_id
top_proposal_id = 1;
proposal status = 1;
*/
require (_id == top_proposal_id, "Wrong id."); //Require correct proposal to be chosen.
require (_id != 0, "_id != 0"); //Cannot initialise the genesis proposal.
running_proposal_id = _id; //Update running proposal id.
top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposa_id is necessary in the submission function above for the first submission after each proposal.
proposal[_id].status = 1; //Set proposal status to 'ongoing'.
uint init_sell_size = proposal[pa_proposal_id].next_init_tranche_size; //Init sell tranche size.
proposal[_id].side[1].current_tranche_size = init_sell_size;
uint minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume;
uint dai_out = add(wmul(990000000000000000, proposal[_id].amount), minimum_sell_volume);
uint net_balance = net_dai_balance;
uint init_buy_size;
//Make sure that the contract is always running a positive net dai balance:
if (dai_out > net_balance){
init_buy_size = wmul(wdiv(init_sell_size, minimum_sell_volume), sub(dai_out, net_balance));
}
else{
init_buy_size = init_sell_size;
}
proposal[_id].side[0].current_tranche_size = init_buy_size;
current_tranche_start = uint40(now);
proposal[_id].proposal_start = uint40(now);
top_param = 0; //reset top param.
emit InitProposal (_id, init_buy_size, init_sell_size);
}
function reset() external{
require (uint40(now) - proposal[pa_proposal_id].proposal_start > proposal[pa_proposal_id].reset_time_period, "Reset time not elapsed."); //Tests amount of time since last proposal passed.
uint id = ++nonce;
//Set proposal data:
proposal[id].beneficiary = msg.sender;
proposal[id].next_min_prop_period = proposal[pa_proposal_id].next_min_prop_period;
proposal[id].next_init_tranche_size = proposal[pa_proposal_id].next_init_tranche_size;
proposal[id].next_init_price_data = proposal[pa_proposal_id].next_init_price_data;
proposal[id].next_reject_spread_threshold = proposal[pa_proposal_id].next_reject_spread_threshold;
uint next_minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume;
proposal[id].next_minimum_sell_volume = next_minimum_sell_volume;
proposal[id].reset_time_period = proposal[pa_proposal_id].reset_time_period;
require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished.
running_proposal_id = uint40(id); //Update running proposal id.
top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposal_id is necessary in the submission function above for the first submission after each proposal.
proposal[id].status = 4; //Set proposal status to 'ongoing reset proposal'.
proposal[id].side[0].current_tranche_size = next_minimum_sell_volume;
proposal[id].side[1].current_tranche_size = next_minimum_sell_volume;
//Set as size of tranche as minimum sell volume.
current_tranche_start = uint40(now);
proposal[id].proposal_start = uint40(now);
top_param = 0; //reset top param.
emit Reset(id);
}
function all_trades_common(uint _id, uint _side, uint _tranche_size) internal view returns (uint current_tranche_t) {
require (_id == running_proposal_id, "Wrong id."); //User can only trade on currently running proposal.
require (proposal[_id].side[_side].current_tranche_size == _tranche_size, "Wrong tranche size."); //Make sure the user's selected tranche size is the current tranche size. Without this they may choose arbitrary tranches and then loose tokens.
require (proposal[_id].side[_side].tranche[_tranche_size].price == 0, "Tranche already closed."); //Check tranche is still open.
current_tranche_t = proposal[_id].side[_side].current_tranche_total;
}
function buy_sell_common(uint _id, uint _input_amount, uint _side, uint _tranche_size, uint _current_dai_price) internal {
uint current_tranche_t = all_trades_common(_id, _side, _tranche_size);
require (wmul(add(_input_amount, current_tranche_t), _current_dai_price) < _tranche_size, "Try closing tranche."); //Makes sure users cannot send tokens beyond or even up to the current tranche size since this is for the tranche close function.
proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = add(proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender], _input_amount); //Record proposal balance.
proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time = sub(now, current_tranche_start); //Set time of most recent trade so 2nd to last trade time can be recorded. Offset by current_tranche_start to account for zero initial value.
proposal[_id].side[_side].current_tranche_total = add(current_tranche_t, _input_amount); //Update current_tranche_total.
emit NewTrancheTotal (_side, current_tranche_t + _input_amount);
}
function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external {
//Set correct amount of dai
buy_sell_common(_id, _input_dai_amount, 0, _tranche_size, WAD); //For buying _dai_amount = _input_dai_amount. Dai price = 1.0.
ERC20Interface.transferFrom(msg.sender, address(this), _input_dai_amount); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction.
}
function sell(uint _id, uint _input_token_amount, uint _tranche_size) external {
//Set correct amount of dai
buy_sell_common(_id, _input_token_amount, 1, _tranche_size, calculate_price(1, now)); //For selling, the current dai amount must be used based on current price.
burn(_input_token_amount); //Remove user governance tokens. SafeMath should revert with insufficient funds.
}
function close_buy_sell_common_1(uint _id, uint _side, uint _tranche_size) internal returns(uint price, uint final_trade_price, uint current_tranche_t) {
current_tranche_t = all_trades_common(_id, _side, _tranche_size);
price = calculate_price(_side, add(proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time, current_tranche_start)); //(WAD) Sets price for all traders.
final_trade_price = calculate_price(_side, now);
proposal[_id].side[_side].tranche[_tranche_size].price = price; //(WAD) Sets price for all traders.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_price = final_trade_price; //(WAD) Sets price for only the final trader.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_address = msg.sender; //Record address of final trade.
proposal[_id].side[_side].current_tranche_total = 0; //Reset current_tranche_total to zero.
}
function close_buy_sell_common_2(uint _id, uint _balance_amount, uint _side, uint _tranche_size, uint _input_dai_amount, uint _current_tranche_t_dai, uint _this_tranche_tokens_total) internal {
require (add(_input_dai_amount, _current_tranche_t_dai) >= _tranche_size, "Not enough to close."); //Check that the user has provided enough dai or equivalent to close the tranche.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = _balance_amount; //Record final trade amount.
if (proposal[_id].side[(_side+1)%2].tranche[proposal[_id].side[(_side+1)%2].current_tranche_size].price != 0){ //Check whether tranche for other side has closed.
current_tranche_start = uint40(now); //Reset timer for next tranche.
proposal[_id].side[_side].total_tokens_traded = add(proposal[_id].side[_side].total_tokens_traded, _this_tranche_tokens_total);
proposal[_id].side[(_side+1)%2].total_tokens_traded = add(proposal[_id].side[(_side+1)%2].total_tokens_traded, lct_tokens_traded); //Sets total tokens traded on each side now that tranches on both sides have closed (using lct_tokens_traded which was recorded when the other side closed.)
proposal[_id].side[_side].total_dai_traded = add(proposal[_id].side[_side].total_dai_traded, _tranche_size);
proposal[_id].side[(_side+1)%2].total_dai_traded = add(proposal[_id].side[(_side+1)%2].total_dai_traded, proposal[_id].side[(_side+1)%2].current_tranche_size); //Add total dai traded in tranche to total_dai_traded.
//Add total dai traded in tranche to total_dai_traded.
if (proposal[_id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume) { //if sell volume has reached the minimum and reset has not already happened: then reset the tranche sizes on both sides to the same value.
uint new_size = mul(_tranche_size, 2);
proposal[_id].side[0].current_tranche_size = new_size;
proposal[_id].side[1].current_tranche_size = new_size;
//Set both tranche sizes to the same size.
}
else {
proposal[_id].side[_side].current_tranche_size = mul(_tranche_size, 2);
proposal[_id].side[(_side+1)%2].current_tranche_size = mul(proposal[_id].side[(_side+1)%2].current_tranche_size, 2); //Double the current tranche sizes.
}
}
else{
lct_tokens_traded = _this_tranche_tokens_total; //Records last closed tranche tokens traded total for when both tranches close.
}
emit TrancheClose (_side, _tranche_size, _this_tranche_tokens_total); //Users must check when both sides have closed and then calculate total traded themselves by summing the TrancheClose data.
}
function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external {
(uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 0, _tranche_size);
uint dai_amount_left = sub(_tranche_size, current_tranche_t); //Calculates new amount of dai for user to give.
uint this_tranche_tokens_total = add(wmul(current_tranche_t,price), wmul(dai_amount_left, final_trade_price)); //Update total_tokens_traded
close_buy_sell_common_2(_id, dai_amount_left, 0, _tranche_size, _input_dai_amount, current_tranche_t, this_tranche_tokens_total);
ERC20Interface.transferFrom(msg.sender, address(this), dai_amount_left); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction.
}
function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external {
(uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 1, _tranche_size);
uint dai_amount_left = sub(_tranche_size, wmul(current_tranche_t, price)); //Calculates dai_amount_left in tranche which is based on the price the other sellers will pay, not the current price.
uint token_equiv_left = wdiv(dai_amount_left, final_trade_price); //Calculate amount of tokens to give user based on dai amount left.
uint equiv_input_dai_amount = wmul(_input_token_amount, final_trade_price); //Equivalent amount of dai at current prices based on the user amount of tokens.
uint this_tranche_tokens_total = add(current_tranche_t, token_equiv_left); //Update total_tokens_traded
close_buy_sell_common_2(_id, token_equiv_left, 1, _tranche_size, equiv_input_dai_amount, wmul(current_tranche_t, price), this_tranche_tokens_total);
burn(token_equiv_left); //Remove user governance tokens. SafeMath should revert with insufficient funds.
}
function accept_prop() external {
uint id = running_proposal_id;
require (proposal[id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached.
//Collect state data into memory for calculating prices:
uint current_total_dai_sold = proposal[id].side[0].total_dai_traded;
uint previous_total_dai_bought = proposal[pa_proposal_id].side[1].total_dai_traded;
uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded;
uint proposal_amount = proposal[id].amount;
uint accept_current_p_amount;
uint accept_previous_p_amount;
//Calculate where attacker's capital will be spent for accept case and reject case:
if (current_total_dai_sold < add(previous_total_dai_bought, proposal_amount)){
accept_current_p_amount = proposal_amount;
//accept_previous_p_amount = 0 by default.
}
else{
//accept_current_p_amount = 0 by default.
accept_previous_p_amount = proposal_amount;
}
//Attacker aims to attack at weakest point. The assumed ratio of z_a_p to y_a_p determines where attack is spending capital i.e. where they are attacking. So the attacker will aim to spend the most where the amount of dai is lowest, since this will have the greatest effect on price. Or in other words we want to know the minimum of the minimum prices.
uint accept_price = wmul(wdiv(sub(current_total_dai_sold, accept_current_p_amount), current_total_tokens_bought), wdiv(proposal[pa_proposal_id].side[1].total_tokens_traded, add(accept_previous_p_amount, previous_total_dai_bought))); //Minimum non-manipulated price.
if (accept_price > WAD){ //If proposal accepted: (change to require later)
proposal[id].status = 2;
ERC20Interface.transfer(proposal[id].beneficiary, proposal[id].amount);
pa_proposal_id = running_proposal_id;
running_proposal_id = 0;
_supply = sub(add(_supply, proposal[id].side[0].total_tokens_traded), proposal[id].side[1].total_tokens_traded);
net_dai_balance = sub(add(net_dai_balance, current_total_dai_sold), add(wmul(990000000000000000, proposal_amount), proposal[id].side[1].total_dai_traded)); //Update net_dai_balance
}
emit AcceptAttempt (accept_price, wdiv(current_total_dai_sold, current_total_tokens_bought), wdiv(proposal[id].side[1].total_dai_traded, proposal[id].side[1].total_tokens_traded));
}
function reject_prop_spread() external {
uint id = running_proposal_id;
require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal.
uint recent_buy_price = proposal[id].side[0].tranche[proposal[id].side[0].current_tranche_size].price; //Price of current tranche.
uint recent_sell_price = proposal[id].side[1].tranche[proposal[id].side[1].current_tranche_size].price;
if (recent_buy_price == 0) { //Checks whether current tranche has closed. If not then latest price is calculated.
recent_buy_price = calculate_price(0, now);
}
if (recent_sell_price == 0) {
recent_sell_price = calculate_price(1, now);
}
uint spread = wmul(recent_buy_price, recent_sell_price); //Spread based on current tranche using auction prices that have not finished when necessary. You cannot manipulate spread to be larger so naive price is used.
if (spread > proposal[pa_proposal_id].next_reject_spread_threshold){
proposal[id].status = 3;
running_proposal_id = 0;
}
emit RejectSpreadAttempt(spread);
}
function reject_prop_time() external {
uint id = running_proposal_id;
require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal.
require (now - proposal[id].proposal_start > proposal[id].prop_period, "Still has time.");
proposal[id].status = 3;
running_proposal_id = 0;
emit TimeRejected();
}
function accept_reset() external {
uint id = running_proposal_id;
uint current_total_dai_bought = proposal[id].side[1].total_dai_traded;
uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded;
uint current_total_tokens_sold = proposal[id].side[1].total_tokens_traded;
require (current_total_dai_bought >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached.
require (proposal[id].status == 4, "Not reset proposal."); //Check that this is a reset proposal rather than just any standard proposal.
proposal[id].status = 2; //Proposal accepted
pa_proposal_id = running_proposal_id;
running_proposal_id = 0;
_supply = sub(add(_supply, current_total_tokens_bought), current_total_tokens_sold); //Update supply.
//Net_dai_balance remains the same since equal dai is traded on both sides and proposal.amount = 0.
emit ResetAccepted(wdiv(proposal[id].side[0].total_dai_traded, current_total_tokens_bought), wdiv(current_total_dai_bought, current_total_tokens_sold));
}
function redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){
require (proposal[_id].status == _status, "incorrect status");
amount = proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender];
proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = 0; //Set balance to zero.
}
function redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) {
require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Other side never finished."); //Make sure that both sides of the tranche finished.
amount = wmul(redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function.
}
function buy_redeem(uint _id, uint _tranche_size) external {
mint(redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens.
}
function sell_redeem(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai.
}
function buy_refund_reject(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai.
}
function sell_refund_reject(uint _id, uint _tranche_size) external {
mint(redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens.
}
function buy_refund_accept(uint _id, uint _tranche_size) external {
require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished.
ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 2)); //User paid with dai so they get back dai.
}
function sell_refund_accept(uint _id, uint _tranche_size) external {
require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished.
mint(redeem_refund_common(_id, _tranche_size, 1, 2));//User paid with tokens so they get back tokens.
}
//Functions for redeeming final trades:
function final_redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){
require (proposal[_id].status == _status, "Incorrect status");
require (proposal[_id].side[_side].tranche[_tranche_size].final_trade_address == msg.sender, "Wasn't you.");
amount = proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount;
proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = 0; //Set balance to zero.
}
function final_redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) {
require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Try refund."); //Make sure that both sides of the tranche finished.
amount = wmul(final_redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].final_trade_price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function.
}
function final_buy_redeem(uint _id, uint _tranche_size) external {
mint(final_redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens.
}
function final_sell_redeem(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, final_redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai.
}
function final_buy_refund_reject(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, final_redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai.
}
function final_sell_refund_reject(uint _id, uint _tranche_size) external {
mint(final_redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens.
}
constructor(uint _init_price, ERC20 _ERC20Interface) public { //(WAD) _init_price is defined as dai_amount/token_amount. _supply is defined in the TokenBase constructor.
ERC20Interface = _ERC20Interface; //fakeDai contract. Use checksum version of address.
//Genesis proposal which will be used by first proposal.
proposal[0].status = 2;
proposal[0].beneficiary = address(this); //Because the submission of first proposal would break the erc20 transfer function if address(0) is used, therefore, we use this address.
proposal[0].amount = 0; //For first proposal submission, 0/100 will be returned to contract address.
proposal[0].prop_period = 1;
proposal[0].next_min_prop_period = 1;
proposal[0].next_init_tranche_size = wmul(_supply, _init_price)/100;
proposal[0].next_init_price_data = [wdiv(WAD, wmul(40*WAD, _init_price)), wdiv(_init_price, 2*WAD) , 1003858241594480000, 10**17]; //Price here is defined as [amount received by user after proposal]/[amount given by user before].
//Price should double every 30 mins. Buy price starts above sell price at max potential price - vice versa for sell price. p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)). e = 2**(1/180). Value of f defines 10 seconds as 1 int.
proposal[0].next_reject_spread_threshold = 7 * WAD;
proposal[0].next_minimum_sell_volume = wmul(_supply, _init_price)/100; //(10 ** -6) dai minimum sell volume.
proposal[0].reset_time_period = 10;
proposal[0].proposal_start = uint40(now);
//Genesis trade values:
proposal[0].side[0].total_dai_traded = wmul(_supply, _init_price); //0.001 dai initial market cap. (10 ** -6) dai initial price.
proposal[0].side[1].total_dai_traded = wmul(_supply, _init_price);
proposal[0].side[0].total_tokens_traded = _supply;
proposal[0].side[1].total_tokens_traded = _supply;
} //price = total_dai_traded/_supply
}
/// erc20.sol -- API for the ERC20 token standard
// See <https://github.com/ethereum/EIPs/issues/20>.
// This file likely does not meet the threshold of originality
// required for copyright to apply. As a result, this is free and
// unencumbered software belonging to the public domain.
pragma solidity >0.4.20;
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() external view returns (uint);
function balanceOf(address guy) external view returns (uint);
function allowance(address src, address guy) external view returns (uint);
function approve(address guy, uint wad) external returns (bool);
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
pragma solidity ^0.5.0;
contract onchain_gov_events{
event NewSubmission (uint40 indexed id, address beneficiary, uint amount, uint next_init_tranche_size, uint[4] next_init_price_data, uint next_reject_spread_threshold, uint next_minimum_sell_volume, uint40 prop_period, uint40 next_min_prop_period, uint40 reset_time_period);
event InitProposal (uint40 id, uint init_buy_tranche, uint init_sell_tranche);
event Reset(uint id);
event NewTrancheTotal (uint side, uint current_tranche_t); //Measured in terms of given token.
event TrancheClose (uint side, uint current_tranche_size, uint this_tranche_tokens_total); //Indicates tranche that closed and whether both or just one side have now closed.
event AcceptAttempt (uint accept_price, uint average_buy_dai_price, uint average_sell_dai_price); //
event RejectSpreadAttempt(uint spread);
event TimeRejected();
event ResetAccepted(uint average_buy_dai_price, uint average_sell_dai_price);
}
interface IOnchain_gov{
function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint);
function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint);
function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool);
function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) external returns (bool);
function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool);
function calculate_price(uint _side, uint _now) external view returns (uint p);
function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external;
function init_proposal(uint40 _id) external;
function reset() external;
function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external;
function sell(uint _id, uint _input_token_amount, uint _tranche_size) external;
function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external;
function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external;
function accept_prop() external;
function reject_prop_spread() external;
function reject_prop_time() external;
function accept_reset() external;
function buy_redeem(uint _id, uint _tranche_size) external;
function sell_redeem(uint _id, uint _tranche_size) external;
function buy_refund_reject(uint _id, uint _tranche_size) external;
function sell_refund_reject(uint _id, uint _tranche_size) external;
function buy_refund_accept(uint _id, uint _tranche_size) external;
function sell_refund_accept(uint _id, uint _tranche_size) external;
function final_buy_redeem(uint _id, uint _tranche_size) external;
function final_sell_redeem(uint _id, uint _tranche_size) external;
function final_buy_refund_reject(uint _id, uint _tranche_size) external;
function final_sell_refund_reject(uint _id, uint _tranche_size) external;
}
//27 functions
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >0.4.13;
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
uint constant WAD = 10 ** 18;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function wpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : WAD;
for (n /= 2; n != 0; n /= 2) {
x = wmul(x, x);
if (n % 2 != 0) {
z = wmul(z, x);
}
}
}
}
// Copyright (C) 2020 Benjamin M J D Wang
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.0;
import "base.sol";
contract proposal_tokens is TokenBase(0) {
//Proposal mappings
mapping (uint => Proposal) internal proposal; //proposal id is taken from nonce.
struct Proposal { //Records all data that is submitted during proposal submission.
address beneficiary;
uint amount; //(WAD)
uint next_init_tranche_size; //(WAD)
uint[4] next_init_price_data; //Array of data for next proposal [initial buy price (WAD), initial sell price (WAD), base (WAD), exponent factor (int)]
uint next_reject_spread_threshold; //(WAD)
uint next_minimum_sell_volume; //(WAD)
uint8 status; //0 = not submitted or not ongoing, 1 = ongoing, 2 = accepted, 3 = rejected, 4 = ongoing reset proposal.
uint40 prop_period; //(int) How long users have to prop before prop rejected.
uint40 next_min_prop_period; //(int) Minimum prop period for the next proposal.
uint40 reset_time_period; //(int) Time period necessary for proposal to be reset.
uint40 proposal_start; //(int) This is to provide a time limit for the length of proposals.
mapping (uint => Side) side; //Each side of proposal
}
struct Side { //Current tranche data for this interval.
uint current_tranche_total; //This is in units of given tokens rather than only dai tokens: dai for buying, proposal token for selling. For selling, total equivalent dai tokens is calculated within the function.
uint total_dai_traded; //Used for calculating acceptance/rejection thresholds.
uint total_tokens_traded; //Used for calculating acceptance/rejection thresholds.
uint current_tranche_size; //(WAD) This is maximum amount or equivalent maximum amount of dai tokens the tranche can be.
mapping (uint => Tranche) tranche; //Data for each tranche that must be recorded. Size of tranche will be the uint tranche id.
}
struct Tranche {
uint price; //(WAD) Final tranche price for each tranche. Price is defined as if the user is selling their respective token types to the proposal so price increases over time to incentivise selling. Buy price is price of dai in proposal tokens where sell price is the price in dai.
uint final_trade_price;
uint recent_trade_time;
uint final_trade_amount;
address final_trade_address;
mapping (address => uint) balance; //(WAD)
mapping (address => mapping (address => uint256)) approvals;
}
uint40 internal nonce; // Nonce for submitted proposals that have a higher param regardless of whether they are chosen or not. Will also be used for chosen proposals.
uint40 public top_proposal_id; //Id of current top proposal.
uint40 public running_proposal_id; //id of the proposal that has been initialised.
uint40 public pa_proposal_id; //Previously accepted proposal id.
uint40 current_tranche_start; //(int)
uint public top_param; //(WAD)
uint internal lct_tokens_traded; //Records the total tokens traded for the tranche on the first side to close. This means that this calculation won't need to be repeated when both sides close.
uint internal net_dai_balance; //The contract's dai balance as if all redemptions and refunds are collected in full, re-calculated at the end of every accepted proposal.
function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint) {
return proposal[_id].side[_side].tranche[_tranche].balance[_account];
}
function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint) {
return proposal[_id].side[_side].tranche[_tranche].approvals[_from][_guy];
}
function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool) {
return proposal_transfer_from(_id, _side, _tranche, msg.sender, _to, _amount);
}
event ProposalTokenTransfer(address from, address to, uint amount);
function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount)
public
returns (bool)
{
if (_from != msg.sender) {
proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender] = sub(proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender], _amount); //Revert if funds insufficient.
}
proposal[_id].side[_side].tranche[_tranche].balance[_from] = sub(proposal[_id].side[_side].tranche[_tranche].balance[_from], _amount);
proposal[_id].side[_side].tranche[_tranche].balance[_to] = add(proposal[_id].side[_side].tranche[_tranche].balance[_to], _amount);
emit ProposalTokenTransfer(_from, _to, _amount);
return true;
}
event ProposalTokenApproval(address account, address guy, uint amount);
function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool) {
proposal[_id].side[_side].tranche[_tranche].approvals[msg.sender][_guy] = _amount;
emit ProposalTokenApproval(msg.sender, _guy, _amount);
return true;
}
}
/// base.sol -- basic ERC20 implementation
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.4.23;
import "erc20.sol";
import "math.sol";
contract TokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() external view returns (uint) {
return _supply;
}
function balanceOf(address src) external view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) external view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) external returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //Revert if funds insufficient.
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) external returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
event Mint(address guy, uint wad);
event Burn(address guy, uint wad);
function mint(uint wad) internal { //Note: _supply constant
_balances[msg.sender] = add(_balances[msg.sender], wad);
emit Mint(msg.sender, wad);
}
function burn(uint wad) internal { //Note: _supply constant
_balances[msg.sender] = sub(_balances[msg.sender], wad); //Revert if funds insufficient.
emit Burn(msg.sender, wad);
}
}
// Copyright (C) 2020 Benjamin M J D Wang
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.0;
import "gov_interface_v2.sol"; //Import governance contract interface.
import "proposal_tokens_v3.sol"; //proposal tokens data structure and transfer functions.
contract onchain_gov_BMJDW2020 is IOnchain_gov, proposal_tokens, onchain_gov_events{
ERC20 public ERC20Interface;
function calculate_price(uint _side, uint _now) public view returns (uint p) { //Function could also be internal if users can calculate price themselves easily.
uint[4] memory price_data = proposal[pa_proposal_id].next_init_price_data;
p = wmul(price_data[_side], wpow(price_data[2], mul(price_data[3], sub(_now, current_tranche_start))/WAD)); //(WAD)
//p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD));
/**
p = WAD
p1 = WAD
e = WAD
f = int
now = int
start = int
*/
}
function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external {
uint param = wdiv(_amount, mul(_next_min_prop_period, _prop_period)); //_next_min_prop_period is purely an anti-spam prevention to stop spammers submitting proposals with very small amounts. Assume WAD since _next_min_prop_period * _prop_period may result in large number.
require(param > top_param, "param < top_param");
require(_prop_period > proposal[pa_proposal_id].next_min_prop_period, "prop_period < minimum"); //check that voting period is greater than the next_min_prop_period of the last accepted proposal.
top_param = param; //Sets current top param to that of the resently submitted proposal.
ERC20Interface.transferFrom(msg.sender, address(this), _amount / 100);//Takes proposer's deposit in dai. This must throw an error and revert if the user does not have enough funds available.
ERC20Interface.transfer(proposal[top_proposal_id].beneficiary, proposal[top_proposal_id].amount / 100); ////Pays back the deposit to the old top proposer in dai.
uint id = ++nonce; //Implicit conversion to uint256
top_proposal_id = uint40(id); //set top proposal id and is used as id for recording data.
//Store all new proposal data:
proposal[id].beneficiary = msg.sender;
proposal[id].amount = _amount;
proposal[id].next_init_tranche_size = _next_init_tranche_size;
proposal[id].next_init_price_data = _next_init_price_data;
proposal[id].next_reject_spread_threshold = _next_reject_spread_threshold;
proposal[id].next_minimum_sell_volume = _next_minimum_sell_volume;
proposal[id].prop_period = _prop_period;
proposal[id].next_min_prop_period = _next_min_prop_period;
proposal[id].reset_time_period = _reset_time_period;
emit NewSubmission(uint40(id), msg.sender, _amount, _next_init_tranche_size, _next_init_price_data, _next_reject_spread_threshold, _next_minimum_sell_volume, _prop_period, _next_min_prop_period, _reset_time_period);
}
function init_proposal(uint40 _id) external { //'sell' and 'buy' indicate sell and buy side from the user perspective in the context of governance tokens even though it is in reference to dai.
require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished.
/**
When proposal has ended and was accepted:
pa_proposal_id = running_proposal_id
running_proposal_id = 0
When proposal has ended and was rejected:
pa_proposal_id remains the same.
running_proposal_id = 0
When initialised:
running_proposal_id = top_proposal_id
top_proposal_id = 1;
proposal status = 1;
*/
require (_id == top_proposal_id, "Wrong id."); //Require correct proposal to be chosen.
require (_id != 0, "_id != 0"); //Cannot initialise the genesis proposal.
running_proposal_id = _id; //Update running proposal id.
top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposa_id is necessary in the submission function above for the first submission after each proposal.
proposal[_id].status = 1; //Set proposal status to 'ongoing'.
uint init_sell_size = proposal[pa_proposal_id].next_init_tranche_size; //Init sell tranche size.
proposal[_id].side[1].current_tranche_size = init_sell_size;
uint minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume;
uint dai_out = add(wmul(990000000000000000, proposal[_id].amount), minimum_sell_volume);
uint net_balance = net_dai_balance;
uint init_buy_size;
//Make sure that the contract is always running a positive net dai balance:
if (dai_out > net_balance){
init_buy_size = wmul(wdiv(init_sell_size, minimum_sell_volume), sub(dai_out, net_balance));
}
else{
init_buy_size = init_sell_size;
}
proposal[_id].side[0].current_tranche_size = init_buy_size;
current_tranche_start = uint40(now);
proposal[_id].proposal_start = uint40(now);
top_param = 0; //reset top param.
emit InitProposal (_id, init_buy_size, init_sell_size);
}
function reset() external{
require (uint40(now) - proposal[pa_proposal_id].proposal_start > proposal[pa_proposal_id].reset_time_period, "Reset time not elapsed."); //Tests amount of time since last proposal passed.
uint id = ++nonce;
//Set proposal data:
proposal[id].beneficiary = msg.sender;
proposal[id].next_min_prop_period = proposal[pa_proposal_id].next_min_prop_period;
proposal[id].next_init_tranche_size = proposal[pa_proposal_id].next_init_tranche_size;
proposal[id].next_init_price_data = proposal[pa_proposal_id].next_init_price_data;
proposal[id].next_reject_spread_threshold = proposal[pa_proposal_id].next_reject_spread_threshold;
uint next_minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume;
proposal[id].next_minimum_sell_volume = next_minimum_sell_volume;
proposal[id].reset_time_period = proposal[pa_proposal_id].reset_time_period;
require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished.
running_proposal_id = uint40(id); //Update running proposal id.
top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposal_id is necessary in the submission function above for the first submission after each proposal.
proposal[id].status = 4; //Set proposal status to 'ongoing reset proposal'.
proposal[id].side[0].current_tranche_size = next_minimum_sell_volume;
proposal[id].side[1].current_tranche_size = next_minimum_sell_volume;
//Set as size of tranche as minimum sell volume.
current_tranche_start = uint40(now);
proposal[id].proposal_start = uint40(now);
top_param = 0; //reset top param.
emit Reset(id);
}
function all_trades_common(uint _id, uint _side, uint _tranche_size) internal view returns (uint current_tranche_t) {
require (_id == running_proposal_id, "Wrong id."); //User can only trade on currently running proposal.
require (proposal[_id].side[_side].current_tranche_size == _tranche_size, "Wrong tranche size."); //Make sure the user's selected tranche size is the current tranche size. Without this they may choose arbitrary tranches and then loose tokens.
require (proposal[_id].side[_side].tranche[_tranche_size].price == 0, "Tranche already closed."); //Check tranche is still open.
current_tranche_t = proposal[_id].side[_side].current_tranche_total;
}
function buy_sell_common(uint _id, uint _input_amount, uint _side, uint _tranche_size, uint _current_dai_price) internal {
uint current_tranche_t = all_trades_common(_id, _side, _tranche_size);
require (wmul(add(_input_amount, current_tranche_t), _current_dai_price) < _tranche_size, "Try closing tranche."); //Makes sure users cannot send tokens beyond or even up to the current tranche size since this is for the tranche close function.
proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = add(proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender], _input_amount); //Record proposal balance.
proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time = sub(now, current_tranche_start); //Set time of most recent trade so 2nd to last trade time can be recorded. Offset by current_tranche_start to account for zero initial value.
proposal[_id].side[_side].current_tranche_total = add(current_tranche_t, _input_amount); //Update current_tranche_total.
emit NewTrancheTotal (_side, current_tranche_t + _input_amount);
}
function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external {
//Set correct amount of dai
buy_sell_common(_id, _input_dai_amount, 0, _tranche_size, WAD); //For buying _dai_amount = _input_dai_amount. Dai price = 1.0.
ERC20Interface.transferFrom(msg.sender, address(this), _input_dai_amount); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction.
}
function sell(uint _id, uint _input_token_amount, uint _tranche_size) external {
//Set correct amount of dai
buy_sell_common(_id, _input_token_amount, 1, _tranche_size, calculate_price(1, now)); //For selling, the current dai amount must be used based on current price.
burn(_input_token_amount); //Remove user governance tokens. SafeMath should revert with insufficient funds.
}
function close_buy_sell_common_1(uint _id, uint _side, uint _tranche_size) internal returns(uint price, uint final_trade_price, uint current_tranche_t) {
current_tranche_t = all_trades_common(_id, _side, _tranche_size);
price = calculate_price(_side, add(proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time, current_tranche_start)); //(WAD) Sets price for all traders.
final_trade_price = calculate_price(_side, now);
proposal[_id].side[_side].tranche[_tranche_size].price = price; //(WAD) Sets price for all traders.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_price = final_trade_price; //(WAD) Sets price for only the final trader.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_address = msg.sender; //Record address of final trade.
proposal[_id].side[_side].current_tranche_total = 0; //Reset current_tranche_total to zero.
}
function close_buy_sell_common_2(uint _id, uint _balance_amount, uint _side, uint _tranche_size, uint _input_dai_amount, uint _current_tranche_t_dai, uint _this_tranche_tokens_total) internal {
require (add(_input_dai_amount, _current_tranche_t_dai) >= _tranche_size, "Not enough to close."); //Check that the user has provided enough dai or equivalent to close the tranche.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = _balance_amount; //Record final trade amount.
if (proposal[_id].side[(_side+1)%2].tranche[proposal[_id].side[(_side+1)%2].current_tranche_size].price != 0){ //Check whether tranche for other side has closed.
current_tranche_start = uint40(now); //Reset timer for next tranche.
proposal[_id].side[_side].total_tokens_traded = add(proposal[_id].side[_side].total_tokens_traded, _this_tranche_tokens_total);
proposal[_id].side[(_side+1)%2].total_tokens_traded = add(proposal[_id].side[(_side+1)%2].total_tokens_traded, lct_tokens_traded); //Sets total tokens traded on each side now that tranches on both sides have closed (using lct_tokens_traded which was recorded when the other side closed.)
proposal[_id].side[_side].total_dai_traded = add(proposal[_id].side[_side].total_dai_traded, _tranche_size);
proposal[_id].side[(_side+1)%2].total_dai_traded = add(proposal[_id].side[(_side+1)%2].total_dai_traded, proposal[_id].side[(_side+1)%2].current_tranche_size); //Add total dai traded in tranche to total_dai_traded.
//Add total dai traded in tranche to total_dai_traded.
if (proposal[_id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume) { //if sell volume has reached the minimum and reset has not already happened: then reset the tranche sizes on both sides to the same value.
uint new_size = mul(_tranche_size, 2);
proposal[_id].side[0].current_tranche_size = new_size;
proposal[_id].side[1].current_tranche_size = new_size;
//Set both tranche sizes to the same size.
}
else {
proposal[_id].side[_side].current_tranche_size = mul(_tranche_size, 2);
proposal[_id].side[(_side+1)%2].current_tranche_size = mul(proposal[_id].side[(_side+1)%2].current_tranche_size, 2); //Double the current tranche sizes.
}
}
else{
lct_tokens_traded = _this_tranche_tokens_total; //Records last closed tranche tokens traded total for when both tranches close.
}
emit TrancheClose (_side, _tranche_size, _this_tranche_tokens_total); //Users must check when both sides have closed and then calculate total traded themselves by summing the TrancheClose data.
}
function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external {
(uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 0, _tranche_size);
uint dai_amount_left = sub(_tranche_size, current_tranche_t); //Calculates new amount of dai for user to give.
uint this_tranche_tokens_total = add(wmul(current_tranche_t,price), wmul(dai_amount_left, final_trade_price)); //Update total_tokens_traded
close_buy_sell_common_2(_id, dai_amount_left, 0, _tranche_size, _input_dai_amount, current_tranche_t, this_tranche_tokens_total);
ERC20Interface.transferFrom(msg.sender, address(this), dai_amount_left); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction.
}
function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external {
(uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 1, _tranche_size);
uint dai_amount_left = sub(_tranche_size, wmul(current_tranche_t, price)); //Calculates dai_amount_left in tranche which is based on the price the other sellers will pay, not the current price.
uint token_equiv_left = wdiv(dai_amount_left, final_trade_price); //Calculate amount of tokens to give user based on dai amount left.
uint equiv_input_dai_amount = wmul(_input_token_amount, final_trade_price); //Equivalent amount of dai at current prices based on the user amount of tokens.
uint this_tranche_tokens_total = add(current_tranche_t, token_equiv_left); //Update total_tokens_traded
close_buy_sell_common_2(_id, token_equiv_left, 1, _tranche_size, equiv_input_dai_amount, wmul(current_tranche_t, price), this_tranche_tokens_total);
burn(token_equiv_left); //Remove user governance tokens. SafeMath should revert with insufficient funds.
}
function accept_prop() external {
uint id = running_proposal_id;
require (proposal[id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached.
//Collect state data into memory for calculating prices:
uint current_total_dai_sold = proposal[id].side[0].total_dai_traded;
uint previous_total_dai_bought = proposal[pa_proposal_id].side[1].total_dai_traded;
uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded;
uint proposal_amount = proposal[id].amount;
uint accept_current_p_amount;
uint accept_previous_p_amount;
//Calculate where attacker's capital will be spent for accept case and reject case:
if (current_total_dai_sold < add(previous_total_dai_bought, proposal_amount)){
accept_current_p_amount = proposal_amount;
//accept_previous_p_amount = 0 by default.
}
else{
//accept_current_p_amount = 0 by default.
accept_previous_p_amount = proposal_amount;
}
//Attacker aims to attack at weakest point. The assumed ratio of z_a_p to y_a_p determines where attack is spending capital i.e. where they are attacking. So the attacker will aim to spend the most where the amount of dai is lowest, since this will have the greatest effect on price. Or in other words we want to know the minimum of the minimum prices.
uint accept_price = wmul(wdiv(sub(current_total_dai_sold, accept_current_p_amount), current_total_tokens_bought), wdiv(proposal[pa_proposal_id].side[1].total_tokens_traded, add(accept_previous_p_amount, previous_total_dai_bought))); //Minimum non-manipulated price.
if (accept_price > WAD){ //If proposal accepted: (change to require later)
proposal[id].status = 2;
ERC20Interface.transfer(proposal[id].beneficiary, proposal[id].amount);
pa_proposal_id = running_proposal_id;
running_proposal_id = 0;
_supply = sub(add(_supply, proposal[id].side[0].total_tokens_traded), proposal[id].side[1].total_tokens_traded);
net_dai_balance = sub(add(net_dai_balance, current_total_dai_sold), add(wmul(990000000000000000, proposal_amount), proposal[id].side[1].total_dai_traded)); //Update net_dai_balance
}
emit AcceptAttempt (accept_price, wdiv(current_total_dai_sold, current_total_tokens_bought), wdiv(proposal[id].side[1].total_dai_traded, proposal[id].side[1].total_tokens_traded));
}
function reject_prop_spread() external {
uint id = running_proposal_id;
require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal.
uint recent_buy_price = proposal[id].side[0].tranche[proposal[id].side[0].current_tranche_size].price; //Price of current tranche.
uint recent_sell_price = proposal[id].side[1].tranche[proposal[id].side[1].current_tranche_size].price;
if (recent_buy_price == 0) { //Checks whether current tranche has closed. If not then latest price is calculated.
recent_buy_price = calculate_price(0, now);
}
if (recent_sell_price == 0) {
recent_sell_price = calculate_price(1, now);
}
uint spread = wmul(recent_buy_price, recent_sell_price); //Spread based on current tranche using auction prices that have not finished when necessary. You cannot manipulate spread to be larger so naive price is used.
if (spread > proposal[pa_proposal_id].next_reject_spread_threshold){
proposal[id].status = 3;
running_proposal_id = 0;
}
emit RejectSpreadAttempt(spread);
}
function reject_prop_time() external {
uint id = running_proposal_id;
require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal.
require (now - proposal[id].proposal_start > proposal[id].prop_period, "Still has time.");
proposal[id].status = 3;
running_proposal_id = 0;
emit TimeRejected();
}
function accept_reset() external {
uint id = running_proposal_id;
uint current_total_dai_bought = proposal[id].side[1].total_dai_traded;
uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded;
uint current_total_tokens_sold = proposal[id].side[1].total_tokens_traded;
require (current_total_dai_bought >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached.
require (proposal[id].status == 4, "Not reset proposal."); //Check that this is a reset proposal rather than just any standard proposal.
proposal[id].status = 2; //Proposal accepted
pa_proposal_id = running_proposal_id;
running_proposal_id = 0;
_supply = sub(add(_supply, current_total_tokens_bought), current_total_tokens_sold); //Update supply.
//Net_dai_balance remains the same since equal dai is traded on both sides and proposal.amount = 0.
emit ResetAccepted(wdiv(proposal[id].side[0].total_dai_traded, current_total_tokens_bought), wdiv(current_total_dai_bought, current_total_tokens_sold));
}
function redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){
require (proposal[_id].status == _status, "incorrect status");
amount = proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender];
proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = 0; //Set balance to zero.
}
function redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) {
require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Other side never finished."); //Make sure that both sides of the tranche finished.
amount = wmul(redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function.
}
function buy_redeem(uint _id, uint _tranche_size) external {
mint(redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens.
}
function sell_redeem(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai.
}
function buy_refund_reject(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai.
}
function sell_refund_reject(uint _id, uint _tranche_size) external {
mint(redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens.
}
function buy_refund_accept(uint _id, uint _tranche_size) external {
require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished.
ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 2)); //User paid with dai so they get back dai.
}
function sell_refund_accept(uint _id, uint _tranche_size) external {
require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished.
mint(redeem_refund_common(_id, _tranche_size, 1, 2));//User paid with tokens so they get back tokens.
}
//Functions for redeeming final trades:
function final_redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){
require (proposal[_id].status == _status, "Incorrect status");
require (proposal[_id].side[_side].tranche[_tranche_size].final_trade_address == msg.sender, "Wasn't you.");
amount = proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount;
proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = 0; //Set balance to zero.
}
function final_redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) {
require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Try refund."); //Make sure that both sides of the tranche finished.
amount = wmul(final_redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].final_trade_price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function.
}
function final_buy_redeem(uint _id, uint _tranche_size) external {
mint(final_redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens.
}
function final_sell_redeem(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, final_redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai.
}
function final_buy_refund_reject(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, final_redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai.
}
function final_sell_refund_reject(uint _id, uint _tranche_size) external {
mint(final_redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens.
}
constructor(uint _init_price, ERC20 _ERC20Interface) public { //(WAD) _init_price is defined as dai_amount/token_amount. _supply is defined in the TokenBase constructor.
ERC20Interface = _ERC20Interface; //fakeDai contract. Use checksum version of address.
//Genesis proposal which will be used by first proposal.
proposal[0].status = 2;
proposal[0].beneficiary = address(this); //Because the submission of first proposal would break the erc20 transfer function if address(0) is used, therefore, we use this address.
proposal[0].amount = 0; //For first proposal submission, 0/100 will be returned to contract address.
proposal[0].prop_period = 1;
proposal[0].next_min_prop_period = 1;
proposal[0].next_init_tranche_size = wmul(_supply, _init_price)/100;
proposal[0].next_init_price_data = [wdiv(WAD, wmul(40*WAD, _init_price)), wdiv(_init_price, 2*WAD) , 1003858241594480000, 10**17]; //Price here is defined as [amount received by user after proposal]/[amount given by user before].
//Price should double every 30 mins. Buy price starts above sell price at max potential price - vice versa for sell price. p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)). e = 2**(1/180). Value of f defines 10 seconds as 1 int.
proposal[0].next_reject_spread_threshold = 7 * WAD;
proposal[0].next_minimum_sell_volume = wmul(_supply, _init_price)/100; //(10 ** -6) dai minimum sell volume.
proposal[0].reset_time_period = 10;
proposal[0].proposal_start = uint40(now);
//Genesis trade values:
proposal[0].side[0].total_dai_traded = wmul(_supply, _init_price); //0.001 dai initial market cap. (10 ** -6) dai initial price.
proposal[0].side[1].total_dai_traded = wmul(_supply, _init_price);
proposal[0].side[0].total_tokens_traded = _supply;
proposal[0].side[1].total_tokens_traded = _supply;
} //price = total_dai_traded/_supply
}
/// erc20.sol -- API for the ERC20 token standard
// See <https://github.com/ethereum/EIPs/issues/20>.
// This file likely does not meet the threshold of originality
// required for copyright to apply. As a result, this is free and
// unencumbered software belonging to the public domain.
pragma solidity >0.4.20;
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() external view returns (uint);
function balanceOf(address guy) external view returns (uint);
function allowance(address src, address guy) external view returns (uint);
function approve(address guy, uint wad) external returns (bool);
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
pragma solidity ^0.5.0;
contract onchain_gov_events{
event NewSubmission (uint40 indexed id, address beneficiary, uint amount, uint next_init_tranche_size, uint[4] next_init_price_data, uint next_reject_spread_threshold, uint next_minimum_sell_volume, uint40 prop_period, uint40 next_min_prop_period, uint40 reset_time_period);
event InitProposal (uint40 id, uint init_buy_tranche, uint init_sell_tranche);
event Reset(uint id);
event NewTrancheTotal (uint side, uint current_tranche_t); //Measured in terms of given token.
event TrancheClose (uint side, uint current_tranche_size, uint this_tranche_tokens_total); //Indicates tranche that closed and whether both or just one side have now closed.
event AcceptAttempt (uint accept_price, uint average_buy_dai_price, uint average_sell_dai_price); //
event RejectSpreadAttempt(uint spread);
event TimeRejected();
event ResetAccepted(uint average_buy_dai_price, uint average_sell_dai_price);
}
interface IOnchain_gov{
function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint);
function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint);
function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool);
function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) external returns (bool);
function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool);
function calculate_price(uint _side, uint _now) external view returns (uint p);
function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external;
function init_proposal(uint40 _id) external;
function reset() external;
function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external;
function sell(uint _id, uint _input_token_amount, uint _tranche_size) external;
function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external;
function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external;
function accept_prop() external;
function reject_prop_spread() external;
function reject_prop_time() external;
function accept_reset() external;
function buy_redeem(uint _id, uint _tranche_size) external;
function sell_redeem(uint _id, uint _tranche_size) external;
function buy_refund_reject(uint _id, uint _tranche_size) external;
function sell_refund_reject(uint _id, uint _tranche_size) external;
function buy_refund_accept(uint _id, uint _tranche_size) external;
function sell_refund_accept(uint _id, uint _tranche_size) external;
function final_buy_redeem(uint _id, uint _tranche_size) external;
function final_sell_redeem(uint _id, uint _tranche_size) external;
function final_buy_refund_reject(uint _id, uint _tranche_size) external;
function final_sell_refund_reject(uint _id, uint _tranche_size) external;
}
//27 functions
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >0.4.13;
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
uint constant WAD = 10 ** 18;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function wpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : WAD;
for (n /= 2; n != 0; n /= 2) {
x = wmul(x, x);
if (n % 2 != 0) {
z = wmul(z, x);
}
}
}
}
// Copyright (C) 2020 Benjamin M J D Wang
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.0;
import "base.sol";
contract proposal_tokens is TokenBase(0) {
//Proposal mappings
mapping (uint => Proposal) internal proposal; //proposal id is taken from nonce.
struct Proposal { //Records all data that is submitted during proposal submission.
address beneficiary;
uint amount; //(WAD)
uint next_init_tranche_size; //(WAD)
uint[4] next_init_price_data; //Array of data for next proposal [initial buy price (WAD), initial sell price (WAD), base (WAD), exponent factor (int)]
uint next_reject_spread_threshold; //(WAD)
uint next_minimum_sell_volume; //(WAD)
uint8 status; //0 = not submitted or not ongoing, 1 = ongoing, 2 = accepted, 3 = rejected, 4 = ongoing reset proposal.
uint40 prop_period; //(int) How long users have to prop before prop rejected.
uint40 next_min_prop_period; //(int) Minimum prop period for the next proposal.
uint40 reset_time_period; //(int) Time period necessary for proposal to be reset.
uint40 proposal_start; //(int) This is to provide a time limit for the length of proposals.
mapping (uint => Side) side; //Each side of proposal
}
struct Side { //Current tranche data for this interval.
uint current_tranche_total; //This is in units of given tokens rather than only dai tokens: dai for buying, proposal token for selling. For selling, total equivalent dai tokens is calculated within the function.
uint total_dai_traded; //Used for calculating acceptance/rejection thresholds.
uint total_tokens_traded; //Used for calculating acceptance/rejection thresholds.
uint current_tranche_size; //(WAD) This is maximum amount or equivalent maximum amount of dai tokens the tranche can be.
mapping (uint => Tranche) tranche; //Data for each tranche that must be recorded. Size of tranche will be the uint tranche id.
}
struct Tranche {
uint price; //(WAD) Final tranche price for each tranche. Price is defined as if the user is selling their respective token types to the proposal so price increases over time to incentivise selling. Buy price is price of dai in proposal tokens where sell price is the price in dai.
uint final_trade_price;
uint recent_trade_time;
uint final_trade_amount;
address final_trade_address;
mapping (address => uint) balance; //(WAD)
mapping (address => mapping (address => uint256)) approvals;
}
uint40 internal nonce; // Nonce for submitted proposals that have a higher param regardless of whether they are chosen or not. Will also be used for chosen proposals.
uint40 public top_proposal_id; //Id of current top proposal.
uint40 public running_proposal_id; //id of the proposal that has been initialised.
uint40 public pa_proposal_id; //Previously accepted proposal id.
uint40 current_tranche_start; //(int)
uint public top_param; //(WAD)
uint internal lct_tokens_traded; //Records the total tokens traded for the tranche on the first side to close. This means that this calculation won't need to be repeated when both sides close.
uint internal net_dai_balance; //The contract's dai balance as if all redemptions and refunds are collected in full, re-calculated at the end of every accepted proposal.
function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint) {
return proposal[_id].side[_side].tranche[_tranche].balance[_account];
}
function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint) {
return proposal[_id].side[_side].tranche[_tranche].approvals[_from][_guy];
}
function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool) {
return proposal_transfer_from(_id, _side, _tranche, msg.sender, _to, _amount);
}
event ProposalTokenTransfer(address from, address to, uint amount);
function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount)
public
returns (bool)
{
if (_from != msg.sender) {
proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender] = sub(proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender], _amount); //Revert if funds insufficient.
}
proposal[_id].side[_side].tranche[_tranche].balance[_from] = sub(proposal[_id].side[_side].tranche[_tranche].balance[_from], _amount);
proposal[_id].side[_side].tranche[_tranche].balance[_to] = add(proposal[_id].side[_side].tranche[_tranche].balance[_to], _amount);
emit ProposalTokenTransfer(_from, _to, _amount);
return true;
}
event ProposalTokenApproval(address account, address guy, uint amount);
function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool) {
proposal[_id].side[_side].tranche[_tranche].approvals[msg.sender][_guy] = _amount;
emit ProposalTokenApproval(msg.sender, _guy, _amount);
return true;
}
}
/// base.sol -- basic ERC20 implementation
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.4.23;
import "erc20.sol";
import "math.sol";
contract TokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() external view returns (uint) {
return _supply;
}
function balanceOf(address src) external view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) external view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) external returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //Revert if funds insufficient.
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) external returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
event Mint(address guy, uint wad);
event Burn(address guy, uint wad);
function mint(uint wad) internal { //Note: _supply constant
_balances[msg.sender] = add(_balances[msg.sender], wad);
emit Mint(msg.sender, wad);
}
function burn(uint wad) internal { //Note: _supply constant
_balances[msg.sender] = sub(_balances[msg.sender], wad); //Revert if funds insufficient.
emit Burn(msg.sender, wad);
}
}
// Copyright (C) 2020 Benjamin M J D Wang
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.0;
import "gov_interface_v2.sol"; //Import governance contract interface.
import "proposal_tokens_v3.sol"; //proposal tokens data structure and transfer functions.
contract onchain_gov_BMJDW2020 is IOnchain_gov, proposal_tokens, onchain_gov_events{
ERC20 public ERC20Interface;
function calculate_price(uint _side, uint _now) public view returns (uint p) { //Function could also be internal if users can calculate price themselves easily.
uint[4] memory price_data = proposal[pa_proposal_id].next_init_price_data;
p = wmul(price_data[_side], wpow(price_data[2], mul(price_data[3], sub(_now, current_tranche_start))/WAD)); //(WAD)
//p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD));
/**
p = WAD
p1 = WAD
e = WAD
f = int
now = int
start = int
*/
}
function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external {
uint param = wdiv(_amount, mul(_next_min_prop_period, _prop_period)); //_next_min_prop_period is purely an anti-spam prevention to stop spammers submitting proposals with very small amounts. Assume WAD since _next_min_prop_period * _prop_period may result in large number.
require(param > top_param, "param < top_param");
require(_prop_period > proposal[pa_proposal_id].next_min_prop_period, "prop_period < minimum"); //check that voting period is greater than the next_min_prop_period of the last accepted proposal.
top_param = param; //Sets current top param to that of the resently submitted proposal.
ERC20Interface.transferFrom(msg.sender, address(this), _amount / 100);//Takes proposer's deposit in dai. This must throw an error and revert if the user does not have enough funds available.
ERC20Interface.transfer(proposal[top_proposal_id].beneficiary, proposal[top_proposal_id].amount / 100); ////Pays back the deposit to the old top proposer in dai.
uint id = ++nonce; //Implicit conversion to uint256
top_proposal_id = uint40(id); //set top proposal id and is used as id for recording data.
//Store all new proposal data:
proposal[id].beneficiary = msg.sender;
proposal[id].amount = _amount;
proposal[id].next_init_tranche_size = _next_init_tranche_size;
proposal[id].next_init_price_data = _next_init_price_data;
proposal[id].next_reject_spread_threshold = _next_reject_spread_threshold;
proposal[id].next_minimum_sell_volume = _next_minimum_sell_volume;
proposal[id].prop_period = _prop_period;
proposal[id].next_min_prop_period = _next_min_prop_period;
proposal[id].reset_time_period = _reset_time_period;
emit NewSubmission(uint40(id), msg.sender, _amount, _next_init_tranche_size, _next_init_price_data, _next_reject_spread_threshold, _next_minimum_sell_volume, _prop_period, _next_min_prop_period, _reset_time_period);
}
function init_proposal(uint40 _id) external { //'sell' and 'buy' indicate sell and buy side from the user perspective in the context of governance tokens even though it is in reference to dai.
require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished.
/**
When proposal has ended and was accepted:
pa_proposal_id = running_proposal_id
running_proposal_id = 0
When proposal has ended and was rejected:
pa_proposal_id remains the same.
running_proposal_id = 0
When initialised:
running_proposal_id = top_proposal_id
top_proposal_id = 1;
proposal status = 1;
*/
require (_id == top_proposal_id, "Wrong id."); //Require correct proposal to be chosen.
require (_id != 0, "_id != 0"); //Cannot initialise the genesis proposal.
running_proposal_id = _id; //Update running proposal id.
top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposa_id is necessary in the submission function above for the first submission after each proposal.
proposal[_id].status = 1; //Set proposal status to 'ongoing'.
uint init_sell_size = proposal[pa_proposal_id].next_init_tranche_size; //Init sell tranche size.
proposal[_id].side[1].current_tranche_size = init_sell_size;
uint minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume;
uint dai_out = add(wmul(990000000000000000, proposal[_id].amount), minimum_sell_volume);
uint net_balance = net_dai_balance;
uint init_buy_size;
//Make sure that the contract is always running a positive net dai balance:
if (dai_out > net_balance){
init_buy_size = wmul(wdiv(init_sell_size, minimum_sell_volume), sub(dai_out, net_balance));
}
else{
init_buy_size = init_sell_size;
}
proposal[_id].side[0].current_tranche_size = init_buy_size;
current_tranche_start = uint40(now);
proposal[_id].proposal_start = uint40(now);
top_param = 0; //reset top param.
emit InitProposal (_id, init_buy_size, init_sell_size);
}
function reset() external{
require (uint40(now) - proposal[pa_proposal_id].proposal_start > proposal[pa_proposal_id].reset_time_period, "Reset time not elapsed."); //Tests amount of time since last proposal passed.
uint id = ++nonce;
//Set proposal data:
proposal[id].beneficiary = msg.sender;
proposal[id].next_min_prop_period = proposal[pa_proposal_id].next_min_prop_period;
proposal[id].next_init_tranche_size = proposal[pa_proposal_id].next_init_tranche_size;
proposal[id].next_init_price_data = proposal[pa_proposal_id].next_init_price_data;
proposal[id].next_reject_spread_threshold = proposal[pa_proposal_id].next_reject_spread_threshold;
uint next_minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume;
proposal[id].next_minimum_sell_volume = next_minimum_sell_volume;
proposal[id].reset_time_period = proposal[pa_proposal_id].reset_time_period;
require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished.
running_proposal_id = uint40(id); //Update running proposal id.
top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposal_id is necessary in the submission function above for the first submission after each proposal.
proposal[id].status = 4; //Set proposal status to 'ongoing reset proposal'.
proposal[id].side[0].current_tranche_size = next_minimum_sell_volume;
proposal[id].side[1].current_tranche_size = next_minimum_sell_volume;
//Set as size of tranche as minimum sell volume.
current_tranche_start = uint40(now);
proposal[id].proposal_start = uint40(now);
top_param = 0; //reset top param.
emit Reset(id);
}
function all_trades_common(uint _id, uint _side, uint _tranche_size) internal view returns (uint current_tranche_t) {
require (_id == running_proposal_id, "Wrong id."); //User can only trade on currently running proposal.
require (proposal[_id].side[_side].current_tranche_size == _tranche_size, "Wrong tranche size."); //Make sure the user's selected tranche size is the current tranche size. Without this they may choose arbitrary tranches and then loose tokens.
require (proposal[_id].side[_side].tranche[_tranche_size].price == 0, "Tranche already closed."); //Check tranche is still open.
current_tranche_t = proposal[_id].side[_side].current_tranche_total;
}
function buy_sell_common(uint _id, uint _input_amount, uint _side, uint _tranche_size, uint _current_dai_price) internal {
uint current_tranche_t = all_trades_common(_id, _side, _tranche_size);
require (wmul(add(_input_amount, current_tranche_t), _current_dai_price) < _tranche_size, "Try closing tranche."); //Makes sure users cannot send tokens beyond or even up to the current tranche size since this is for the tranche close function.
proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = add(proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender], _input_amount); //Record proposal balance.
proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time = sub(now, current_tranche_start); //Set time of most recent trade so 2nd to last trade time can be recorded. Offset by current_tranche_start to account for zero initial value.
proposal[_id].side[_side].current_tranche_total = add(current_tranche_t, _input_amount); //Update current_tranche_total.
emit NewTrancheTotal (_side, current_tranche_t + _input_amount);
}
function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external {
//Set correct amount of dai
buy_sell_common(_id, _input_dai_amount, 0, _tranche_size, WAD); //For buying _dai_amount = _input_dai_amount. Dai price = 1.0.
ERC20Interface.transferFrom(msg.sender, address(this), _input_dai_amount); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction.
}
function sell(uint _id, uint _input_token_amount, uint _tranche_size) external {
//Set correct amount of dai
buy_sell_common(_id, _input_token_amount, 1, _tranche_size, calculate_price(1, now)); //For selling, the current dai amount must be used based on current price.
burn(_input_token_amount); //Remove user governance tokens. SafeMath should revert with insufficient funds.
}
function close_buy_sell_common_1(uint _id, uint _side, uint _tranche_size) internal returns(uint price, uint final_trade_price, uint current_tranche_t) {
current_tranche_t = all_trades_common(_id, _side, _tranche_size);
price = calculate_price(_side, add(proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time, current_tranche_start)); //(WAD) Sets price for all traders.
final_trade_price = calculate_price(_side, now);
proposal[_id].side[_side].tranche[_tranche_size].price = price; //(WAD) Sets price for all traders.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_price = final_trade_price; //(WAD) Sets price for only the final trader.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_address = msg.sender; //Record address of final trade.
proposal[_id].side[_side].current_tranche_total = 0; //Reset current_tranche_total to zero.
}
function close_buy_sell_common_2(uint _id, uint _balance_amount, uint _side, uint _tranche_size, uint _input_dai_amount, uint _current_tranche_t_dai, uint _this_tranche_tokens_total) internal {
require (add(_input_dai_amount, _current_tranche_t_dai) >= _tranche_size, "Not enough to close."); //Check that the user has provided enough dai or equivalent to close the tranche.
proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = _balance_amount; //Record final trade amount.
if (proposal[_id].side[(_side+1)%2].tranche[proposal[_id].side[(_side+1)%2].current_tranche_size].price != 0){ //Check whether tranche for other side has closed.
current_tranche_start = uint40(now); //Reset timer for next tranche.
proposal[_id].side[_side].total_tokens_traded = add(proposal[_id].side[_side].total_tokens_traded, _this_tranche_tokens_total);
proposal[_id].side[(_side+1)%2].total_tokens_traded = add(proposal[_id].side[(_side+1)%2].total_tokens_traded, lct_tokens_traded); //Sets total tokens traded on each side now that tranches on both sides have closed (using lct_tokens_traded which was recorded when the other side closed.)
proposal[_id].side[_side].total_dai_traded = add(proposal[_id].side[_side].total_dai_traded, _tranche_size);
proposal[_id].side[(_side+1)%2].total_dai_traded = add(proposal[_id].side[(_side+1)%2].total_dai_traded, proposal[_id].side[(_side+1)%2].current_tranche_size); //Add total dai traded in tranche to total_dai_traded.
//Add total dai traded in tranche to total_dai_traded.
if (proposal[_id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume) { //if sell volume has reached the minimum and reset has not already happened: then reset the tranche sizes on both sides to the same value.
uint new_size = mul(_tranche_size, 2);
proposal[_id].side[0].current_tranche_size = new_size;
proposal[_id].side[1].current_tranche_size = new_size;
//Set both tranche sizes to the same size.
}
else {
proposal[_id].side[_side].current_tranche_size = mul(_tranche_size, 2);
proposal[_id].side[(_side+1)%2].current_tranche_size = mul(proposal[_id].side[(_side+1)%2].current_tranche_size, 2); //Double the current tranche sizes.
}
}
else{
lct_tokens_traded = _this_tranche_tokens_total; //Records last closed tranche tokens traded total for when both tranches close.
}
emit TrancheClose (_side, _tranche_size, _this_tranche_tokens_total); //Users must check when both sides have closed and then calculate total traded themselves by summing the TrancheClose data.
}
function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external {
(uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 0, _tranche_size);
uint dai_amount_left = sub(_tranche_size, current_tranche_t); //Calculates new amount of dai for user to give.
uint this_tranche_tokens_total = add(wmul(current_tranche_t,price), wmul(dai_amount_left, final_trade_price)); //Update total_tokens_traded
close_buy_sell_common_2(_id, dai_amount_left, 0, _tranche_size, _input_dai_amount, current_tranche_t, this_tranche_tokens_total);
ERC20Interface.transferFrom(msg.sender, address(this), dai_amount_left); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction.
}
function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external {
(uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 1, _tranche_size);
uint dai_amount_left = sub(_tranche_size, wmul(current_tranche_t, price)); //Calculates dai_amount_left in tranche which is based on the price the other sellers will pay, not the current price.
uint token_equiv_left = wdiv(dai_amount_left, final_trade_price); //Calculate amount of tokens to give user based on dai amount left.
uint equiv_input_dai_amount = wmul(_input_token_amount, final_trade_price); //Equivalent amount of dai at current prices based on the user amount of tokens.
uint this_tranche_tokens_total = add(current_tranche_t, token_equiv_left); //Update total_tokens_traded
close_buy_sell_common_2(_id, token_equiv_left, 1, _tranche_size, equiv_input_dai_amount, wmul(current_tranche_t, price), this_tranche_tokens_total);
burn(token_equiv_left); //Remove user governance tokens. SafeMath should revert with insufficient funds.
}
function accept_prop() external {
uint id = running_proposal_id;
require (proposal[id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached.
//Collect state data into memory for calculating prices:
uint current_total_dai_sold = proposal[id].side[0].total_dai_traded;
uint previous_total_dai_bought = proposal[pa_proposal_id].side[1].total_dai_traded;
uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded;
uint proposal_amount = proposal[id].amount;
uint accept_current_p_amount;
uint accept_previous_p_amount;
//Calculate where attacker's capital will be spent for accept case and reject case:
if (current_total_dai_sold < add(previous_total_dai_bought, proposal_amount)){
accept_current_p_amount = proposal_amount;
//accept_previous_p_amount = 0 by default.
}
else{
//accept_current_p_amount = 0 by default.
accept_previous_p_amount = proposal_amount;
}
//Attacker aims to attack at weakest point. The assumed ratio of z_a_p to y_a_p determines where attack is spending capital i.e. where they are attacking. So the attacker will aim to spend the most where the amount of dai is lowest, since this will have the greatest effect on price. Or in other words we want to know the minimum of the minimum prices.
uint accept_price = wmul(wdiv(sub(current_total_dai_sold, accept_current_p_amount), current_total_tokens_bought), wdiv(proposal[pa_proposal_id].side[1].total_tokens_traded, add(accept_previous_p_amount, previous_total_dai_bought))); //Minimum non-manipulated price.
if (accept_price > WAD){ //If proposal accepted: (change to require later)
proposal[id].status = 2;
ERC20Interface.transfer(proposal[id].beneficiary, proposal[id].amount);
pa_proposal_id = running_proposal_id;
running_proposal_id = 0;
_supply = sub(add(_supply, proposal[id].side[0].total_tokens_traded), proposal[id].side[1].total_tokens_traded);
net_dai_balance = sub(add(net_dai_balance, current_total_dai_sold), add(wmul(990000000000000000, proposal_amount), proposal[id].side[1].total_dai_traded)); //Update net_dai_balance
}
emit AcceptAttempt (accept_price, wdiv(current_total_dai_sold, current_total_tokens_bought), wdiv(proposal[id].side[1].total_dai_traded, proposal[id].side[1].total_tokens_traded));
}
function reject_prop_spread() external {
uint id = running_proposal_id;
require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal.
uint recent_buy_price = proposal[id].side[0].tranche[proposal[id].side[0].current_tranche_size].price; //Price of current tranche.
uint recent_sell_price = proposal[id].side[1].tranche[proposal[id].side[1].current_tranche_size].price;
if (recent_buy_price == 0) { //Checks whether current tranche has closed. If not then latest price is calculated.
recent_buy_price = calculate_price(0, now);
}
if (recent_sell_price == 0) {
recent_sell_price = calculate_price(1, now);
}
uint spread = wmul(recent_buy_price, recent_sell_price); //Spread based on current tranche using auction prices that have not finished when necessary. You cannot manipulate spread to be larger so naive price is used.
if (spread > proposal[pa_proposal_id].next_reject_spread_threshold){
proposal[id].status = 3;
running_proposal_id = 0;
}
emit RejectSpreadAttempt(spread);
}
function reject_prop_time() external {
uint id = running_proposal_id;
require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal.
require (now - proposal[id].proposal_start > proposal[id].prop_period, "Still has time.");
proposal[id].status = 3;
running_proposal_id = 0;
emit TimeRejected();
}
function accept_reset() external {
uint id = running_proposal_id;
uint current_total_dai_bought = proposal[id].side[1].total_dai_traded;
uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded;
uint current_total_tokens_sold = proposal[id].side[1].total_tokens_traded;
require (current_total_dai_bought >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached.
require (proposal[id].status == 4, "Not reset proposal."); //Check that this is a reset proposal rather than just any standard proposal.
proposal[id].status = 2; //Proposal accepted
pa_proposal_id = running_proposal_id;
running_proposal_id = 0;
_supply = sub(add(_supply, current_total_tokens_bought), current_total_tokens_sold); //Update supply.
//Net_dai_balance remains the same since equal dai is traded on both sides and proposal.amount = 0.
emit ResetAccepted(wdiv(proposal[id].side[0].total_dai_traded, current_total_tokens_bought), wdiv(current_total_dai_bought, current_total_tokens_sold));
}
function redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){
require (proposal[_id].status == _status, "incorrect status");
amount = proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender];
proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = 0; //Set balance to zero.
}
function redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) {
require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Other side never finished."); //Make sure that both sides of the tranche finished.
amount = wmul(redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function.
}
function buy_redeem(uint _id, uint _tranche_size) external {
mint(redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens.
}
function sell_redeem(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai.
}
function buy_refund_reject(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai.
}
function sell_refund_reject(uint _id, uint _tranche_size) external {
mint(redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens.
}
function buy_refund_accept(uint _id, uint _tranche_size) external {
require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished.
ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 2)); //User paid with dai so they get back dai.
}
function sell_refund_accept(uint _id, uint _tranche_size) external {
require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished.
mint(redeem_refund_common(_id, _tranche_size, 1, 2));//User paid with tokens so they get back tokens.
}
//Functions for redeeming final trades:
function final_redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){
require (proposal[_id].status == _status, "Incorrect status");
require (proposal[_id].side[_side].tranche[_tranche_size].final_trade_address == msg.sender, "Wasn't you.");
amount = proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount;
proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = 0; //Set balance to zero.
}
function final_redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) {
require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Try refund."); //Make sure that both sides of the tranche finished.
amount = wmul(final_redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].final_trade_price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function.
}
function final_buy_redeem(uint _id, uint _tranche_size) external {
mint(final_redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens.
}
function final_sell_redeem(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, final_redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai.
}
function final_buy_refund_reject(uint _id, uint _tranche_size) external {
ERC20Interface.transfer(msg.sender, final_redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai.
}
function final_sell_refund_reject(uint _id, uint _tranche_size) external {
mint(final_redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens.
}
constructor(uint _init_price, ERC20 _ERC20Interface) public { //(WAD) _init_price is defined as dai_amount/token_amount. _supply is defined in the TokenBase constructor.
ERC20Interface = _ERC20Interface; //fakeDai contract. Use checksum version of address.
//Genesis proposal which will be used by first proposal.
proposal[0].status = 2;
proposal[0].beneficiary = address(this); //Because the submission of first proposal would break the erc20 transfer function if address(0) is used, therefore, we use this address.
proposal[0].amount = 0; //For first proposal submission, 0/100 will be returned to contract address.
proposal[0].prop_period = 1;
proposal[0].next_min_prop_period = 1;
proposal[0].next_init_tranche_size = wmul(_supply, _init_price)/100;
proposal[0].next_init_price_data = [wdiv(WAD, wmul(40*WAD, _init_price)), wdiv(_init_price, 2*WAD) , 1003858241594480000, 10**17]; //Price here is defined as [amount received by user after proposal]/[amount given by user before].
//Price should double every 30 mins. Buy price starts above sell price at max potential price - vice versa for sell price. p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)). e = 2**(1/180). Value of f defines 10 seconds as 1 int.
proposal[0].next_reject_spread_threshold = 7 * WAD;
proposal[0].next_minimum_sell_volume = wmul(_supply, _init_price)/100; //(10 ** -6) dai minimum sell volume.
proposal[0].reset_time_period = 10;
proposal[0].proposal_start = uint40(now);
//Genesis trade values:
proposal[0].side[0].total_dai_traded = wmul(_supply, _init_price); //0.001 dai initial market cap. (10 ** -6) dai initial price.
proposal[0].side[1].total_dai_traded = wmul(_supply, _init_price);
proposal[0].side[0].total_tokens_traded = _supply;
proposal[0].side[1].total_tokens_traded = _supply;
} //price = total_dai_traded/_supply
}
/// erc20.sol -- API for the ERC20 token standard
// See <https://github.com/ethereum/EIPs/issues/20>.
// This file likely does not meet the threshold of originality
// required for copyright to apply. As a result, this is free and
// unencumbered software belonging to the public domain.
pragma solidity >0.4.20;
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() external view returns (uint);
function balanceOf(address guy) external view returns (uint);
function allowance(address src, address guy) external view returns (uint);
function approve(address guy, uint wad) external returns (bool);
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
pragma solidity ^0.5.0;
contract onchain_gov_events{
event NewSubmission (uint40 indexed id, address beneficiary, uint amount, uint next_init_tranche_size, uint[4] next_init_price_data, uint next_reject_spread_threshold, uint next_minimum_sell_volume, uint40 prop_period, uint40 next_min_prop_period, uint40 reset_time_period);
event InitProposal (uint40 id, uint init_buy_tranche, uint init_sell_tranche);
event Reset(uint id);
event NewTrancheTotal (uint side, uint current_tranche_t); //Measured in terms of given token.
event TrancheClose (uint side, uint current_tranche_size, uint this_tranche_tokens_total); //Indicates tranche that closed and whether both or just one side have now closed.
event AcceptAttempt (uint accept_price, uint average_buy_dai_price, uint average_sell_dai_price); //
event RejectSpreadAttempt(uint spread);
event TimeRejected();
event ResetAccepted(uint average_buy_dai_price, uint average_sell_dai_price);
}
interface IOnchain_gov{
function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint);
function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint);
function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool);
function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) external returns (bool);
function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool);
function calculate_price(uint _side, uint _now) external view returns (uint p);
function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external;
function init_proposal(uint40 _id) external;
function reset() external;
function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external;
function sell(uint _id, uint _input_token_amount, uint _tranche_size) external;
function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external;
function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external;
function accept_prop() external;
function reject_prop_spread() external;
function reject_prop_time() external;
function accept_reset() external;
function buy_redeem(uint _id, uint _tranche_size) external;
function sell_redeem(uint _id, uint _tranche_size) external;
function buy_refund_reject(uint _id, uint _tranche_size) external;
function sell_refund_reject(uint _id, uint _tranche_size) external;
function buy_refund_accept(uint _id, uint _tranche_size) external;
function sell_refund_accept(uint _id, uint _tranche_size) external;
function final_buy_redeem(uint _id, uint _tranche_size) external;
function final_sell_redeem(uint _id, uint _tranche_size) external;
function final_buy_refund_reject(uint _id, uint _tranche_size) external;
function final_sell_refund_reject(uint _id, uint _tranche_size) external;
}
//27 functions
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >0.4.13;
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
uint constant WAD = 10 ** 18;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function wpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : WAD;
for (n /= 2; n != 0; n /= 2) {
x = wmul(x, x);
if (n % 2 != 0) {
z = wmul(z, x);
}
}
}
}
// Copyright (C) 2020 Benjamin M J D Wang
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.0;
import "base.sol";
contract proposal_tokens is TokenBase(0) {
//Proposal mappings
mapping (uint => Proposal) internal proposal; //proposal id is taken from nonce.
struct Proposal { //Records all data that is submitted during proposal submission.
address beneficiary;
uint amount; //(WAD)
uint next_init_tranche_size; //(WAD)
uint[4] next_init_price_data; //Array of data for next proposal [initial buy price (WAD), initial sell price (WAD), base (WAD), exponent factor (int)]
uint next_reject_spread_threshold; //(WAD)
uint next_minimum_sell_volume; //(WAD)
uint8 status; //0 = not submitted or not ongoing, 1 = ongoing, 2 = accepted, 3 = rejected, 4 = ongoing reset proposal.
uint40 prop_period; //(int) How long users have to prop before prop rejected.
uint40 next_min_prop_period; //(int) Minimum prop period for the next proposal.
uint40 reset_time_period; //(int) Time period necessary for proposal to be reset.
uint40 proposal_start; //(int) This is to provide a time limit for the length of proposals.
mapping (uint => Side) side; //Each side of proposal
}
struct Side { //Current tranche data for this interval.
uint current_tranche_total; //This is in units of given tokens rather than only dai tokens: dai for buying, proposal token for selling. For selling, total equivalent dai tokens is calculated within the function.
uint total_dai_traded; //Used for calculating acceptance/rejection thresholds.
uint total_tokens_traded; //Used for calculating acceptance/rejection thresholds.
uint current_tranche_size; //(WAD) This is maximum amount or equivalent maximum amount of dai tokens the tranche can be.
mapping (uint => Tranche) tranche; //Data for each tranche that must be recorded. Size of tranche will be the uint tranche id.
}
struct Tranche {
uint price; //(WAD) Final tranche price for each tranche. Price is defined as if the user is selling their respective token types to the proposal so price increases over time to incentivise selling. Buy price is price of dai in proposal tokens where sell price is the price in dai.
uint final_trade_price;
uint recent_trade_time;
uint final_trade_amount;
address final_trade_address;
mapping (address => uint) balance; //(WAD)
mapping (address => mapping (address => uint256)) approvals;
}
uint40 internal nonce; // Nonce for submitted proposals that have a higher param regardless of whether they are chosen or not. Will also be used for chosen proposals.
uint40 public top_proposal_id; //Id of current top proposal.
uint40 public running_proposal_id; //id of the proposal that has been initialised.
uint40 public pa_proposal_id; //Previously accepted proposal id.
uint40 current_tranche_start; //(int)
uint public top_param; //(WAD)
uint internal lct_tokens_traded; //Records the total tokens traded for the tranche on the first side to close. This means that this calculation won't need to be repeated when both sides close.
uint internal net_dai_balance; //The contract's dai balance as if all redemptions and refunds are collected in full, re-calculated at the end of every accepted proposal.
function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint) {
return proposal[_id].side[_side].tranche[_tranche].balance[_account];
}
function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint) {
return proposal[_id].side[_side].tranche[_tranche].approvals[_from][_guy];
}
function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool) {
return proposal_transfer_from(_id, _side, _tranche, msg.sender, _to, _amount);
}
event ProposalTokenTransfer(address from, address to, uint amount);
function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount)
public
returns (bool)
{
if (_from != msg.sender) {
proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender] = sub(proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender], _amount); //Revert if funds insufficient.
}
proposal[_id].side[_side].tranche[_tranche].balance[_from] = sub(proposal[_id].side[_side].tranche[_tranche].balance[_from], _amount);
proposal[_id].side[_side].tranche[_tranche].balance[_to] = add(proposal[_id].side[_side].tranche[_tranche].balance[_to], _amount);
emit ProposalTokenTransfer(_from, _to, _amount);
return true;
}
event ProposalTokenApproval(address account, address guy, uint amount);
function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool) {
proposal[_id].side[_side].tranche[_tranche].approvals[msg.sender][_guy] = _amount;
emit ProposalTokenApproval(msg.sender, _guy, _amount);
return true;
}
}
|
Set correct amount of dai
|
function sell(uint _id, uint _input_token_amount, uint _tranche_size) external {
}
| 1,816,004 |
./partial_match/1/0xae61DB510cC96D57805Bf3fe4fcCee9365D12fAa/sources/src/SubscriptionManager.sol
|
Grants the KEEPER_ROLE to the provided user. - Throws if the `msg.sender` is not `owner()` On completion: - `newKeeper` is assigned the `KEEPER_ROLE` newKeeper Address to assign the `KEEPER_ROLE`/
|
function grantKeeperRole(address newKeeper) external {
grantRoles(newKeeper, KEEPER_ROLE);
}
| 2,691,164 |
./partial_match/1/0xeA1F21c4f9BDA00BEDB5871E6C0de6746E1e2929/sources/ArkGamesToken.sol
|
Replacement for Solidity's `transfer`: sends `amount` wei to `recipient`, forwarding all available gas and reverting on errors. 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. IMPORTANT: because control is transferred to `recipient`, care must be taken to not create reentrancy vulnerabilities. Consider using {ReentrancyGuard} or the/ solhint-disable-next-line avoid-low-level-calls, avoid-call-value
|
function sendValue(address recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(success, "Address: unable to send value, recipient may have reverted");
}
| 4,207,126 |
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Token {
using SafeMath for uint256;
string public constant name = "Zombie Token";
string public constant symbol = "ZOB";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, uint256 value, address indexed to);
function ERC20Token() public {
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address from, address to, uint256 value) internal {
// Check if the sender has enough balance
require(balanceOf[from] >= value);
// Check for overflow
require(balanceOf[to] + value > balanceOf[to]);
// Save this for an amount double check assertion
uint256 previousBalances = balanceOf[from].add(balanceOf[to]);
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
Transfer(from, to, value);
// Asserts for duplicate check. Should never fail.
assert(balanceOf[from].add(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]);
allowance[from][msg.sender] = allowance[from][msg.sender].sub(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;
Approval(msg.sender, value, spender);
return true;
}
function _mint(address to, uint256 value) internal {
balanceOf[to] = balanceOf[to].add(value);
totalSupply = totalSupply.add(value);
Transfer(0x0, to, value);
}
}
contract zombieToken is Ownable, ERC20Token {
address public invadeAddress;
address public creatorAddress;
uint public preMining = 1000000 * 10 ** 18; //for test purpose
function zombieToken() public {
balanceOf[msg.sender] = preMining;
totalSupply = preMining;
}
function setInvadeAddr(address addr)public onlyOwner {
invadeAddress = addr;
}
function setcreatorAddr(address addr)public onlyOwner {
creatorAddress = addr;
}
function mint(address to, uint256 value) public returns (bool success) {
require(msg.sender==invadeAddress);
_mint(to, value);
return true;
}
function buyCard(address from, uint256 value) public returns (bool success) {
require(msg.sender==creatorAddress);
_transfer(from, creatorAddress, value);
return true;
}
}
|
Set allowance for other address Allows `spender` to spend no more than `value` tokens in your behalf spender The address authorized to spend value the max amount they can spend/
|
function approve(address spender, uint256 value) public returns (bool success) {
allowance[msg.sender][spender] = value;
Approval(msg.sender, value, spender);
return true;
}
| 15,275,806 |
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library StringLib {
/// @notice converts bytes32 into a string.
/// @param bytesToConvert bytes32 array to convert
function bytes32ToString(bytes32 bytesToConvert) internal pure returns (string memory) {
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = bytesToConvert[i];
}
return string(bytesArray);
}
}/*
Copyright 2017-2019 Phillip A. Elsasser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/// @title Math function library with overflow protection inspired by Open Zeppelin
library MathLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
function multiply(uint256 a, uint256 b) pure internal returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MathLib: multiplication overflow");
return c;
}
function divideFractional(
uint256 a,
uint256 numerator,
uint256 denominator
) pure internal returns (uint256)
{
return multiply(a, numerator) / denominator;
}
function subtract(uint256 a, uint256 b) pure internal returns (uint256) {
require(b <= a, "MathLib: subtraction overflow");
return a - b;
}
function add(uint256 a, uint256 b) pure internal returns (uint256) {
uint256 c = a + b;
require(c >= a, "MathLib: addition overflow");
return c;
}
/// @notice determines the amount of needed collateral for a given position (qty and price)
/// @param priceFloor lowest price the contract is allowed to trade before expiration
/// @param priceCap highest price the contract is allowed to trade before expiration
/// @param qtyMultiplier multiplier for qty from base units
/// @param longQty qty to redeem
/// @param shortQty qty to redeem
/// @param price of the trade
function calculateCollateralToReturn(
uint priceFloor,
uint priceCap,
uint qtyMultiplier,
uint longQty,
uint shortQty,
uint price
) pure internal returns (uint)
{
uint neededCollateral = 0;
uint maxLoss;
if (longQty > 0) { // calculate max loss from entry price to floor
if (price <= priceFloor) {
maxLoss = 0;
} else {
maxLoss = subtract(price, priceFloor);
}
neededCollateral = multiply(multiply(maxLoss, longQty), qtyMultiplier);
}
if (shortQty > 0) { // calculate max loss from entry price to ceiling;
if (price >= priceCap) {
maxLoss = 0;
} else {
maxLoss = subtract(priceCap, price);
}
neededCollateral = add(neededCollateral, multiply(multiply(maxLoss, shortQty), qtyMultiplier));
}
return neededCollateral;
}
/// @notice determines the amount of needed collateral for minting a long and short position token
function calculateTotalCollateral(
uint priceFloor,
uint priceCap,
uint qtyMultiplier
) pure internal returns (uint)
{
return multiply(subtract(priceCap, priceFloor), qtyMultiplier);
}
/// @notice calculates the fee in terms of base units of the collateral token per unit pair minted.
function calculateFeePerUnit(
uint priceFloor,
uint priceCap,
uint qtyMultiplier,
uint feeInBasisPoints
) pure internal returns (uint)
{
uint midPrice = add(priceCap, priceFloor) / 2;
return multiply(multiply(midPrice, qtyMultiplier), feeInBasisPoints) / 10000;
}
}
/*
Copyright 2017-2019 Phillip A. Elsasser
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 2017-2019 Phillip A. Elsasser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title 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 MarketContract base contract implement all needed functionality for trading.
/// @notice this is the abstract base contract that all contracts should inherit from to
/// implement different oracle solutions.
/// @author Phil Elsasser <[email protected]>
contract MarketContract is Ownable {
using StringLib for *;
string public CONTRACT_NAME;
address public COLLATERAL_TOKEN_ADDRESS;
address public COLLATERAL_POOL_ADDRESS;
uint public PRICE_CAP;
uint public PRICE_FLOOR;
uint public PRICE_DECIMAL_PLACES; // how to convert the pricing from decimal format (if valid) to integer
uint public QTY_MULTIPLIER; // multiplier corresponding to the value of 1 increment in price to token base units
uint public COLLATERAL_PER_UNIT; // required collateral amount for the full range of outcome tokens
uint public COLLATERAL_TOKEN_FEE_PER_UNIT;
uint public MKT_TOKEN_FEE_PER_UNIT;
uint public EXPIRATION;
uint public SETTLEMENT_DELAY = 1 days;
address public LONG_POSITION_TOKEN;
address public SHORT_POSITION_TOKEN;
// state variables
uint public lastPrice;
uint public settlementPrice;
uint public settlementTimeStamp;
bool public isSettled = false;
// events
event UpdatedLastPrice(uint256 price);
event ContractSettled(uint settlePrice);
/// @param contractNames bytes32 array of names
/// contractName name of the market contract
/// longTokenSymbol symbol for the long token
/// shortTokenSymbol symbol for the short token
/// @param baseAddresses array of 2 addresses needed for our contract including:
/// ownerAddress address of the owner of these contracts.
/// collateralTokenAddress address of the ERC20 token that will be used for collateral and pricing
/// collateralPoolAddress address of our collateral pool contract
/// @param contractSpecs array of unsigned integers including:
/// floorPrice minimum tradeable price of this contract, contract enters settlement if breached
/// capPrice maximum tradeable price of this contract, contract enters settlement if breached
/// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to
/// an integer
/// qtyMultiplier multiply traded qty by this value from base units of collateral token.
/// feeInBasisPoints fee amount in basis points (Collateral token denominated) for minting.
/// mktFeeInBasisPoints fee amount in basis points (MKT denominated) for minting.
/// expirationTimeStamp seconds from epoch that this contract expires and enters settlement
constructor(
bytes32[3] memory contractNames,
address[3] memory baseAddresses,
uint[7] memory contractSpecs
) public
{
PRICE_FLOOR = contractSpecs[0];
PRICE_CAP = contractSpecs[1];
require(PRICE_CAP > PRICE_FLOOR, "PRICE_CAP must be greater than PRICE_FLOOR");
PRICE_DECIMAL_PLACES = contractSpecs[2];
QTY_MULTIPLIER = contractSpecs[3];
EXPIRATION = contractSpecs[6];
require(EXPIRATION > now, "EXPIRATION must be in the future");
require(QTY_MULTIPLIER != 0,"QTY_MULTIPLIER cannot be 0");
COLLATERAL_TOKEN_ADDRESS = baseAddresses[1];
COLLATERAL_POOL_ADDRESS = baseAddresses[2];
COLLATERAL_PER_UNIT = MathLib.calculateTotalCollateral(PRICE_FLOOR, PRICE_CAP, QTY_MULTIPLIER);
COLLATERAL_TOKEN_FEE_PER_UNIT = MathLib.calculateFeePerUnit(
PRICE_FLOOR,
PRICE_CAP,
QTY_MULTIPLIER,
contractSpecs[4]
);
MKT_TOKEN_FEE_PER_UNIT = MathLib.calculateFeePerUnit(
PRICE_FLOOR,
PRICE_CAP,
QTY_MULTIPLIER,
contractSpecs[5]
);
// create long and short tokens
CONTRACT_NAME = contractNames[0].bytes32ToString();
PositionToken longPosToken = new PositionToken(
"MARKET Protocol Long Position Token",
contractNames[1].bytes32ToString(),
uint8(PositionToken.MarketSide.Long)
);
PositionToken shortPosToken = new PositionToken(
"MARKET Protocol Short Position Token",
contractNames[2].bytes32ToString(),
uint8(PositionToken.MarketSide.Short)
);
LONG_POSITION_TOKEN = address(longPosToken);
SHORT_POSITION_TOKEN = address(shortPosToken);
transferOwnership(baseAddresses[0]);
}
/*
// EXTERNAL - onlyCollateralPool METHODS
*/
/// @notice called only by our collateral pool to create long and short position tokens
/// @param qtyToMint qty in base units of how many short and long tokens to mint
/// @param minter address of minter to receive tokens
function mintPositionTokens(
uint256 qtyToMint,
address minter
) external onlyCollateralPool
{
// mint and distribute short and long position tokens to our caller
PositionToken(LONG_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter);
PositionToken(SHORT_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter);
}
/// @notice called only by our collateral pool to redeem long position tokens
/// @param qtyToRedeem qty in base units of how many tokens to redeem
/// @param redeemer address of person redeeming tokens
function redeemLongToken(
uint256 qtyToRedeem,
address redeemer
) external onlyCollateralPool
{
// mint and distribute short and long position tokens to our caller
PositionToken(LONG_POSITION_TOKEN).redeemToken(qtyToRedeem, redeemer);
}
/// @notice called only by our collateral pool to redeem short position tokens
/// @param qtyToRedeem qty in base units of how many tokens to redeem
/// @param redeemer address of person redeeming tokens
function redeemShortToken(
uint256 qtyToRedeem,
address redeemer
) external onlyCollateralPool
{
// mint and distribute short and long position tokens to our caller
PositionToken(SHORT_POSITION_TOKEN).redeemToken(qtyToRedeem, redeemer);
}
/*
// Public METHODS
*/
/// @notice checks to see if a contract is settled, and that the settlement delay has passed
function isPostSettlementDelay() public view returns (bool) {
return isSettled && (now >= (settlementTimeStamp + SETTLEMENT_DELAY));
}
/*
// PRIVATE METHODS
*/
/// @dev checks our last query price to see if our contract should enter settlement due to it being past our
// expiration date or outside of our tradeable ranges.
function checkSettlement() internal {
require(!isSettled, "Contract is already settled"); // already settled.
uint newSettlementPrice;
if (now > EXPIRATION) { // note: miners can cheat this by small increments of time (minutes, not hours)
isSettled = true; // time based expiration has occurred.
newSettlementPrice = lastPrice;
} else if (lastPrice >= PRICE_CAP) { // price is greater or equal to our cap, settle to CAP price
isSettled = true;
newSettlementPrice = PRICE_CAP;
} else if (lastPrice <= PRICE_FLOOR) { // price is lesser or equal to our floor, settle to FLOOR price
isSettled = true;
newSettlementPrice = PRICE_FLOOR;
}
if (isSettled) {
settleContract(newSettlementPrice);
}
}
/// @dev records our final settlement price and fires needed events.
/// @param finalSettlementPrice final query price at time of settlement
function settleContract(uint finalSettlementPrice) internal {
settlementTimeStamp = now;
settlementPrice = finalSettlementPrice;
emit ContractSettled(finalSettlementPrice);
}
/// @notice only able to be called directly by our collateral pool which controls the position tokens
/// for this contract!
modifier onlyCollateralPool {
require(msg.sender == COLLATERAL_POOL_ADDRESS, "Only callable from the collateral pool");
_;
}
}
/*
Copyright 2017-2019 Phillip A. Elsasser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/// @title Position Token
/// @notice A token that represents a claim to a collateral pool and a short or long position.
/// The collateral pool acts as the owner of this contract and controls minting and redemption of these
/// tokens based on locked collateral in the pool.
/// NOTE: We eventually can move all of this logic into a library to avoid deploying all of the logic
/// every time a new market contract is deployed.
/// @author Phil Elsasser <[email protected]>
contract PositionToken is ERC20, Ownable {
string public name;
string public symbol;
uint8 public decimals;
MarketSide public MARKET_SIDE; // 0 = Long, 1 = Short
enum MarketSide { Long, Short}
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 marketSide
) public
{
name = tokenName;
symbol = tokenSymbol;
decimals = 5;
MARKET_SIDE = MarketSide(marketSide);
}
/// @dev Called by our MarketContract (owner) to create a long or short position token. These tokens are minted,
/// and then transferred to our recipient who is the party who is minting these tokens. The collateral pool
/// is the only caller (acts as the owner) because collateral must be deposited / locked prior to minting of new
/// position tokens
/// @param qtyToMint quantity of position tokens to mint (in base units)
/// @param recipient the person minting and receiving these position tokens.
function mintAndSendToken(
uint256 qtyToMint,
address recipient
) external onlyOwner
{
_mint(recipient, qtyToMint);
}
/// @dev Called by our MarketContract (owner) when redemption occurs. This means that either a single user is redeeming
/// both short and long tokens in order to claim their collateral, or the contract has settled, and only a single
/// side of the tokens are needed to redeem (handled by the collateral pool)
/// @param qtyToRedeem quantity of tokens to burn (remove from supply / circulation)
/// @param redeemer the person redeeming these tokens (who are we taking the balance from)
function redeemToken(
uint256 qtyToRedeem,
address redeemer
) external onlyOwner
{
_burn(redeemer, qtyToRedeem);
}
}
/*
Copyright 2017-2019 Phillip A. Elsasser
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 MarketContractRegistryInterface {
function addAddressToWhiteList(address contractAddress) external;
function isAddressWhiteListed(address contractAddress) external view returns (bool);
}
/**
* 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(address(this), spender) == 0));
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must equal true).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
/// @title MarketCollateralPool
/// @notice This collateral pool houses all of the collateral for all market contracts currently in circulation.
/// This pool facilitates locking of collateral and minting / redemption of position tokens for that collateral.
/// @author Phil Elsasser <[email protected]>
contract MarketCollateralPool is Ownable {
using MathLib for uint;
using MathLib for int;
using SafeERC20 for ERC20;
address public marketContractRegistry;
address public mktToken;
mapping(address => uint) public contractAddressToCollateralPoolBalance; // current balance of all collateral committed
mapping(address => uint) public feesCollectedByTokenAddress;
event TokensMinted(
address indexed marketContract,
address indexed user,
address indexed feeToken,
uint qtyMinted,
uint collateralLocked,
uint feesPaid
);
event TokensRedeemed (
address indexed marketContract,
address indexed user,
uint longQtyRedeemed,
uint shortQtyRedeemed,
uint collateralUnlocked
);
constructor(address marketContractRegistryAddress, address mktTokenAddress) public {
marketContractRegistry = marketContractRegistryAddress;
mktToken = mktTokenAddress;
}
/*
// EXTERNAL METHODS
*/
/// @notice Called by a user that would like to mint a new set of long and short token for a specified
/// market contract. This will transfer and lock the correct amount of collateral into the pool
/// and issue them the requested qty of long and short tokens
/// @param marketContractAddress address of the market contract to redeem tokens for
/// @param qtyToMint quantity of long / short tokens to mint.
/// @param isAttemptToPayInMKT if possible, attempt to pay fee's in MKT rather than collateral tokens
function mintPositionTokens(
address marketContractAddress,
uint qtyToMint,
bool isAttemptToPayInMKT
) external onlyWhiteListedAddress(marketContractAddress)
{
MarketContract marketContract = MarketContract(marketContractAddress);
require(!marketContract.isSettled(), "Contract is already settled");
address collateralTokenAddress = marketContract.COLLATERAL_TOKEN_ADDRESS();
uint neededCollateral = MathLib.multiply(qtyToMint, marketContract.COLLATERAL_PER_UNIT());
// the user has selected to pay fees in MKT and those fees are non zero (allowed) OR
// the user has selected not to pay fees in MKT, BUT the collateral token fees are disabled (0) AND the
// MKT fees are enabled (non zero). (If both are zero, no fee exists)
bool isPayFeesInMKT = (isAttemptToPayInMKT &&
marketContract.MKT_TOKEN_FEE_PER_UNIT() != 0) ||
(!isAttemptToPayInMKT &&
marketContract.MKT_TOKEN_FEE_PER_UNIT() != 0 &&
marketContract.COLLATERAL_TOKEN_FEE_PER_UNIT() == 0);
uint feeAmount;
uint totalCollateralTokenTransferAmount;
address feeToken;
if (isPayFeesInMKT) { // fees are able to be paid in MKT
feeAmount = MathLib.multiply(qtyToMint, marketContract.MKT_TOKEN_FEE_PER_UNIT());
totalCollateralTokenTransferAmount = neededCollateral;
feeToken = mktToken;
// EXTERNAL CALL - transferring ERC20 tokens from sender to this contract. User must have called
// ERC20.approve in order for this call to succeed.
ERC20(mktToken).safeTransferFrom(msg.sender, address(this), feeAmount);
} else { // fee are either zero, or being paid in the collateral token
feeAmount = MathLib.multiply(qtyToMint, marketContract.COLLATERAL_TOKEN_FEE_PER_UNIT());
totalCollateralTokenTransferAmount = neededCollateral.add(feeAmount);
feeToken = collateralTokenAddress;
// we will transfer collateral and fees all at once below.
}
// EXTERNAL CALL - transferring ERC20 tokens from sender to this contract. User must have called
// ERC20.approve in order for this call to succeed.
ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransferFrom(msg.sender, address(this), totalCollateralTokenTransferAmount);
if (feeAmount != 0) {
// update the fee's collected balance
feesCollectedByTokenAddress[feeToken] = feesCollectedByTokenAddress[feeToken].add(feeAmount);
}
// Update the collateral pool locked balance.
contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[
marketContractAddress
].add(neededCollateral);
// mint and distribute short and long position tokens to our caller
marketContract.mintPositionTokens(qtyToMint, msg.sender);
emit TokensMinted(
marketContractAddress,
msg.sender,
feeToken,
qtyToMint,
neededCollateral,
feeAmount
);
}
/// @notice Called by a user that currently holds both short and long position tokens and would like to redeem them
/// for their collateral.
/// @param marketContractAddress address of the market contract to redeem tokens for
/// @param qtyToRedeem quantity of long / short tokens to redeem.
function redeemPositionTokens(
address marketContractAddress,
uint qtyToRedeem
) external onlyWhiteListedAddress(marketContractAddress)
{
MarketContract marketContract = MarketContract(marketContractAddress);
marketContract.redeemLongToken(qtyToRedeem, msg.sender);
marketContract.redeemShortToken(qtyToRedeem, msg.sender);
// calculate collateral to return and update pool balance
uint collateralToReturn = MathLib.multiply(qtyToRedeem, marketContract.COLLATERAL_PER_UNIT());
contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[
marketContractAddress
].subtract(collateralToReturn);
// EXTERNAL CALL
// transfer collateral back to user
ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn);
emit TokensRedeemed(
marketContractAddress,
msg.sender,
qtyToRedeem,
qtyToRedeem,
collateralToReturn
);
}
// @notice called by a user after settlement has occurred. This function will finalize all accounting around any
// outstanding positions and return all remaining collateral to the caller. This should only be called after
// settlement has occurred.
/// @param marketContractAddress address of the MARKET Contract being traded.
/// @param longQtyToRedeem qty to redeem of long tokens
/// @param shortQtyToRedeem qty to redeem of short tokens
function settleAndClose(
address marketContractAddress,
uint longQtyToRedeem,
uint shortQtyToRedeem
) external onlyWhiteListedAddress(marketContractAddress)
{
MarketContract marketContract = MarketContract(marketContractAddress);
require(marketContract.isPostSettlementDelay(), "Contract is not past settlement delay");
// burn tokens being redeemed.
if (longQtyToRedeem > 0) {
marketContract.redeemLongToken(longQtyToRedeem, msg.sender);
}
if (shortQtyToRedeem > 0) {
marketContract.redeemShortToken(shortQtyToRedeem, msg.sender);
}
// calculate amount of collateral to return and update pool balances
uint collateralToReturn = MathLib.calculateCollateralToReturn(
marketContract.PRICE_FLOOR(),
marketContract.PRICE_CAP(),
marketContract.QTY_MULTIPLIER(),
longQtyToRedeem,
shortQtyToRedeem,
marketContract.settlementPrice()
);
contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[
marketContractAddress
].subtract(collateralToReturn);
// return collateral tokens
ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn);
emit TokensRedeemed(
marketContractAddress,
msg.sender,
longQtyToRedeem,
shortQtyToRedeem,
collateralToReturn
);
}
/// @dev allows the owner to remove the fees paid into this contract for minting
/// @param feeTokenAddress - address of the erc20 token fees have been paid in
/// @param feeRecipient - Recipient address of fees
function withdrawFees(address feeTokenAddress, address feeRecipient) public onlyOwner {
uint feesAvailableForWithdrawal = feesCollectedByTokenAddress[feeTokenAddress];
require(feesAvailableForWithdrawal != 0, "No fees available for withdrawal");
require(feeRecipient != address(0), "Cannot send fees to null address");
feesCollectedByTokenAddress[feeTokenAddress] = 0;
// EXTERNAL CALL
ERC20(feeTokenAddress).safeTransfer(feeRecipient, feesAvailableForWithdrawal);
}
/// @dev allows the owner to update the mkt token address in use for fees
/// @param mktTokenAddress address of new MKT token
function setMKTTokenAddress(address mktTokenAddress) public onlyOwner {
require(mktTokenAddress != address(0), "Cannot set MKT Token Address To Null");
mktToken = mktTokenAddress;
}
/// @dev allows the owner to update the mkt token address in use for fees
/// @param marketContractRegistryAddress address of new contract registry
function setMarketContractRegistryAddress(address marketContractRegistryAddress) public onlyOwner {
require(marketContractRegistryAddress != address(0), "Cannot set Market Contract Registry Address To Null");
marketContractRegistry = marketContractRegistryAddress;
}
/*
// MODIFIERS
*/
/// @notice only can be called with a market contract address that currently exists in our whitelist
/// this ensure's it is a market contract that has been created by us and therefore has a uniquely created
/// long and short token address. If it didn't we could have spoofed contracts minting tokens with a
/// collateral token that wasn't the same as the intended token.
modifier onlyWhiteListedAddress(address marketContractAddress) {
require(
MarketContractRegistryInterface(marketContractRegistry).isAddressWhiteListed(marketContractAddress),
"Contract is not whitelisted"
);
_;
}
}
|
Called by our MarketContract (owner) to create a long or short position token. These tokens are minted, and then transferred to our recipient who is the party who is minting these tokens. The collateral pool is the only caller (acts as the owner) because collateral must be deposited / locked prior to minting of new position tokens qtyToMint quantity of position tokens to mint (in base units) recipient the person minting and receiving these position tokens.
|
function mintAndSendToken(
uint256 qtyToMint,
address recipient
) external onlyOwner
{
_mint(recipient, qtyToMint);
}
| 1,045,026 |
./partial_match/1/0x475D148484CD934d0c74C6d00fd6e942d9165EC5/sources/XRAID.sol
|
Change the max buy amount _maxBuy The new max buy amount
|
function setMaxBuy(uint256 _maxBuy) external onlyOwner {
emit MaxBuyChanged(maxBuy, _maxBuy);
maxBuy = _maxBuy;
}
| 2,592,257 |
./full_match/1/0x2Ee0d782DC691b4E3DbEb292fB0e83bc5155A6CD/sources/contracts/FantasyFootball.sol
|
view function returning a address's current team
|
function getActiveTeam(address _address) public view returns (uint256[] memory) {
return teams[_address];
}
| 3,072,023 |
./full_match/1/0x991c79DB98dA75eAd9F47286b64f63b878C52354/sources/contracts/external/TransparentUpgradeableProxy.sol
|
Returns the current admin./
|
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
| 16,484,462 |
// File: ComptrollerStorage.sol
pragma solidity ^0.5.16;
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingComptrollerImplementation;
}
// File: ErrorReporter.sol
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// File: STRK.sol
pragma solidity ^0.5.16;
contract STRK {
/// @notice EIP-20 token name for this token
string public constant name = "Strike Token";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "STRK";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 6518828e18; // 6518828 STRK
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Strk token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Strk::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Strk::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Strk::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Strk::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Strk::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Strk::delegateBySig: invalid nonce");
require(now <= expiry, "Strk::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Strk::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Strk::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Strk::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Strk::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Strk::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Strk::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Strk::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Strk::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: Unitroller.sol
pragma solidity ^0.5.16;
/**
* @title ComptrollerCore
* @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`.
* STokens should reference this contract as their comptroller.
*/
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
/**
* @notice Emitted when pendingComptrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () external payable {
// delegate all other functions to current implementation
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => SToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives STRK
bool isStriked;
}
/**
* @notice Official mapping of sTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
struct StrikeMarketState {
/// @notice The market's last updated strikeBorrowIndex or strikeSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
SToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes STRK, per block
uint public strikeRate;
/// @notice The portion of strikeRate that each market currently receives
mapping(address => uint) public strikeSpeeds;
/// @notice The STRK market supply state for each market
mapping(address => StrikeMarketState) public strikeSupplyState;
/// @notice The STRK market borrow state for each market
mapping(address => StrikeMarketState) public strikeBorrowState;
/// @notice The STRK borrow index for each market for each supplier as of the last time they accrued STRK
mapping(address => mapping(address => uint)) public strikeSupplierIndex;
/// @notice The STRK borrow index for each market for each borrower as of the last time they accrued STRK
mapping(address => mapping(address => uint)) public strikeBorrowerIndex;
/// @notice The STRK accrued but not yet transferred to each user
mapping(address => uint) public strikeAccrued;
}
contract ComptrollerV4Storage is ComptrollerV3Storage {
/// @notice The portion of STRK that each constributor receives per block
mapping(address => uint) public strikeContributorSpeeds;
/// @notice Last block at which a contributor's STRK rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
// File: PriceOracle.sol
pragma solidity ^0.5.16;
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a sToken asset
* @param sToken The sToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(SToken sToken) external view returns (uint);
}
// File: EIP20NonStandardInterface.sol
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: EIP20Interface.sol
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: CarefulMath.sol
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Strike
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// File: Exponential.sol
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Strike
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) internal pure returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) internal pure returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) internal pure returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) internal pure returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) internal pure returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) internal pure returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) internal pure returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) internal pure returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) internal pure returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) internal pure returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) internal pure returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) internal pure returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) internal pure returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) internal pure returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) internal pure returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) internal pure returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: InterestRateModel.sol
pragma solidity ^0.5.16;
/**
* @title Strike's InterestRateModel Interface
* @author Strike
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// File: STokenInterfaces.sol
pragma solidity ^0.5.16;
contract STokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-sToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first STokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract STokenInterface is STokenStorage {
/**
* @notice Indicator that this is a SToken contract (for inspection)
*/
bool public constant isSToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address sTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract SErc20Storage {
/**
* @notice Underlying asset for this SToken
*/
address public underlying;
}
contract SErc20Interface is SErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, STokenInterface sTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract SDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract SDelegatorInterface is SDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract SDelegateInterface is SDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
// File: ComptrollerInterface.sol
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata sTokens) external returns (uint[] memory);
function exitMarket(address sToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address sToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address sToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address sToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address sToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address sToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address sToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address sToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address sToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address sTokenBorrowed,
address sTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address sTokenBorrowed,
address sTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address sTokenCollateral,
address sTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address sTokenCollateral,
address sTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address sToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address sToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address sTokenBorrowed,
address sTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
// File: SToken.sol
pragma solidity ^0.5.16;
/**
* @title Strike's SToken Contract
* @notice Abstract base for STokens
* @author Strike
*/
contract SToken is STokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srsTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srsTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srsTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint sTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), sTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this sToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this sToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the SToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the SToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this sToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives sTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives sTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The sToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the sToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of sTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of sTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems sTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of sTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems sTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming sTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems sTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of sTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming sTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The sToken must handle variations between ERC-20 and ETH underlying.
* On success, the sToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The sToken must handle variations between ERC-20 and ETH underlying.
* On success, the sToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The sToken must handle variations between ERC-20 and ETH underlying.
* On success, the sToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this sToken to be liquidated
* @param sTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, STokenInterface sTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = sTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, sTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this sToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param sTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, STokenInterface sTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(sTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify sTokenCollateral market's block number equals current block number */
if (sTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(sTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(sTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(sTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = sTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(sTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(sTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another sToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed sToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of sTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another SToken.
* Its absolutely critical to use msg.sender as the seizer sToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed sToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of sTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The sToken must handle variations between ERC-20 and ETH underlying.
* On success, the sToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// File: Comptroller.sol
pragma solidity ^0.5.16;
/**
* @title Strike's Comptroller Contract
* @author Strike
*/
contract Comptroller is ComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(SToken sToken);
/// @notice Emitted when an account enters a market
event MarketEntered(SToken sToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(SToken sToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(SToken sToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(SToken sToken, string action, bool pauseState);
/// @notice Emitted when market striked status is changed
event MarketStriked(SToken sToken, bool isStriked);
/// @notice Emitted when STRK rate is changed
event NewStrikeRate(uint oldStrikeRate, uint newStrikeRate);
/// @notice Emitted when a new STRK speed is calculated for a market
event StrikeSpeedUpdated(SToken indexed sToken, uint newSpeed);
/// @notice Emitted when STRK is distributed to a supplier
event DistributedSupplierStrike(SToken indexed sToken, address indexed supplier, uint strikeDelta, uint strikeSupplyIndex);
/// @notice Emitted when STRK is distributed to a borrower
event DistributedBorrowerStrike(SToken indexed sToken, address indexed borrower, uint strikeDelta, uint strikeBorrowIndex);
/// @notice Emitted when new Strike speed is set
event ContributorStrikeSpeedUpdated(address indexed contributor, uint newStrikeSpeed);
/// @notice Emitted when Strike is granted
event StrikeGranted(address recipient, uint amount);
/// @notice The threshold above which the flywheel transfers STRK, in wei
uint public constant strikeClaimThreshold = 0.001e18;
/// @notice The initial STRK index for a market
uint224 public constant strikeInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (SToken[] memory) {
SToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param sToken The sToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, SToken sToken) external view returns (bool) {
return markets[address(sToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param sTokens The list of addresses of the sToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory sTokens) public returns (uint[] memory) {
uint len = sTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
SToken sToken = SToken(sTokens[i]);
results[i] = uint(addToMarketInternal(sToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param sToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(SToken sToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(sToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(sToken);
emit MarketEntered(sToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param sTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address sTokenAddress) external returns (uint) {
SToken sToken = SToken(sTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the sToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = sToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(sTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(sToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set sToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete sToken from the account’s list of assets */
// load into memory for faster iteration
SToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == sToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
SToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(sToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param sToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address sToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[sToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[sToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateStrikeSupplyIndex(sToken);
distributeSupplierStrike(sToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param sToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address sToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
sToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param sToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of sTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address sToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(sToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateStrikeSupplyIndex(sToken);
distributeSupplierStrike(sToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address sToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[sToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[sToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, SToken(sToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param sToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address sToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
sToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param sToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address sToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[sToken], "borrow is paused");
if (!markets[sToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[sToken].accountMembership[borrower]) {
// only sTokens may call borrowAllowed if borrower not in market
require(msg.sender == sToken, "sender must be sToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(SToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[sToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(SToken(sToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, SToken(sToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: SToken(sToken).borrowIndex()});
updateStrikeBorrowIndex(sToken, borrowIndex);
distributeBorrowerStrike(sToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param sToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address sToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
sToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param sToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address sToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[sToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: SToken(sToken).borrowIndex()});
updateStrikeBorrowIndex(sToken, borrowIndex);
distributeBorrowerStrike(sToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param sToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address sToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
sToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param sTokenBorrowed Asset which was borrowed by the borrower
* @param sTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address sTokenBorrowed,
address sTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[sTokenBorrowed].isListed || !markets[sTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = SToken(sTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param sTokenBorrowed Asset which was borrowed by the borrower
* @param sTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address sTokenBorrowed,
address sTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
sTokenBorrowed;
sTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param sTokenCollateral Asset which was used as collateral and will be seized
* @param sTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address sTokenCollateral,
address sTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[sTokenCollateral].isListed || !markets[sTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (SToken(sTokenCollateral).comptroller() != SToken(sTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateStrikeSupplyIndex(sTokenCollateral);
distributeSupplierStrike(sTokenCollateral, borrower);
distributeSupplierStrike(sTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param sTokenCollateral Asset which was used as collateral and will be seized
* @param sTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address sTokenCollateral,
address sTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
sTokenCollateral;
sTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param sToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of sTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address sToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(sToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateStrikeSupplyIndex(sToken);
distributeSupplierStrike(sToken, src);
distributeSupplierStrike(sToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param sToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of sTokens to transfer
*/
function transferVerify(address sToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
sToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `sTokenBalance` is the number of sTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint sTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, SToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, SToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param sTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address sTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, SToken(sTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param sTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral sToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
SToken sTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
SToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
SToken asset = assets[i];
// Read the balances and exchange rate from the sToken
(oErr, vars.sTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * sTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.sTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with sTokenModify
if (asset == sTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in sToken.liquidateBorrowFresh)
* @param sTokenBorrowed The address of the borrowed sToken
* @param sTokenCollateral The address of the collateral sToken
* @param actualRepayAmount The amount of sTokenBorrowed underlying to convert into sTokenCollateral tokens
* @return (errorCode, number of sTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address sTokenBorrowed, address sTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(SToken(sTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(SToken(sTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = SToken(sTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param sToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(SToken sToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(sToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(sToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(sToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param sToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(SToken sToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(sToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
sToken.isSToken(); // Sanity check to make sure its really a SToken
markets[address(sToken)] = Market({isListed: true, isStriked: false, collateralFactorMantissa: 0});
_addMarketInternal(address(sToken));
emit MarketListed(sToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address sToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != SToken(sToken), "market already added");
}
allMarkets.push(SToken(sToken));
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(SToken sToken, bool state) public returns (bool) {
require(markets[address(sToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(sToken)] = state;
emit ActionPaused(sToken, "Mint", state);
return state;
}
function _setBorrowPaused(SToken sToken, bool state) public returns (bool) {
require(markets[address(sToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(sToken)] = state;
emit ActionPaused(sToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** STRK Distribution ***/
/**
* @notice Set STRK speed for a single market
* @param sToken The market whose STRK speed to update
* @param strikeSpeed New STRK speed for market
*/
function _setStrikeSpeed(SToken sToken, uint strikeSpeed) public {
require(adminOrInitializing(), "only admin can set strike speed");
setStrikeSpeedInternal(sToken, strikeSpeed);
}
function setStrikeSpeedInternal(SToken sToken, uint strikeSpeed) internal {
uint currentStrikeSpeed = strikeSpeeds[address(sToken)];
if (currentStrikeSpeed != 0) {
// STRK speed could be set to 0 to half liquidity rewards for a market
Exp memory borrowIndex = Exp({
mantissa: sToken.borrowIndex()
});
updateStrikeSupplyIndex(address(sToken));
updateStrikeBorrowIndex(address(sToken), borrowIndex);
} else if (strikeSpeed != 0) {
// Add the STRK market
Market storage market = markets[address(sToken)];
require(market.isListed == true, "strike market is not listed");
if (strikeSupplyState[address(sToken)].index == 0 && strikeSupplyState[address(sToken)].block == 0) {
strikeSupplyState[address(sToken)] = StrikeMarketState({
index: strikeInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (strikeBorrowState[address(sToken)].index == 0 && strikeBorrowState[address(sToken)].block == 0) {
strikeBorrowState[address(sToken)] = StrikeMarketState({
index: strikeInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentStrikeSpeed != strikeSpeed) {
strikeSpeeds[address(sToken)] = strikeSpeed;
emit StrikeSpeedUpdated(sToken, strikeSpeed);
}
}
/**
* @notice Accrue STRK to the market by updating the supply index
* @param sToken The market whose supply index to update
*/
function updateStrikeSupplyIndex(address sToken) internal {
StrikeMarketState storage supplyState = strikeSupplyState[sToken];
uint supplySpeed = strikeSpeeds[sToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = SToken(sToken).totalSupply();
uint strikeAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(strikeAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
strikeSupplyState[sToken] = StrikeMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue STRK to the market by updating the borrow index
* @param sToken The market whose borrow index to update
*/
function updateStrikeBorrowIndex(address sToken, Exp memory marketBorrowIndex) internal {
StrikeMarketState storage borrowState = strikeBorrowState[sToken];
uint borrowSpeed = strikeSpeeds[sToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(SToken(sToken).totalBorrows(), marketBorrowIndex);
uint strikeAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(strikeAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
strikeBorrowState[sToken] = StrikeMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate STRK accrued by a supplier and possibly transfer it to them
* @param sToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute STRK to
*/
function distributeSupplierStrike(address sToken, address supplier) internal {
StrikeMarketState storage supplyState = strikeSupplyState[sToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: strikeSupplierIndex[sToken][supplier]});
strikeSupplierIndex[sToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = strikeInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = SToken(sToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(strikeAccrued[supplier], supplierDelta);
strikeAccrued[supplier] = supplierAccrued;
emit DistributedSupplierStrike(SToken(sToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate STRK accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param sToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute STRK to
*/
function distributeBorrowerStrike(address sToken, address borrower, Exp memory marketBorrowIndex) internal {
StrikeMarketState storage borrowState = strikeBorrowState[sToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: strikeBorrowerIndex[sToken][borrower]});
strikeBorrowerIndex[sToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(SToken(sToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(strikeAccrued[borrower], borrowerDelta);
strikeAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerStrike(SToken(sToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer STRK to the user, if they are above the threshold
* @dev Note: If there is not enough STRK, we do not perform the transfer all.
* @param user The address of the user to transfer STRK to
* @param userAccrued The amount of STRK to (possibly) transfer
* @return The amount of STRK which was NOT transferred to the user
*/
function transferStrike(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
STRK strk = STRK(getSTRKAddress());
uint strikeRemaining = strk.balanceOf(address(this));
if (userAccrued <= strikeRemaining) {
strk.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the strike accrued by holder in all markets
* @param holder The address to claim STRK for
*/
function claimStrike(address holder) public {
return claimStrike(holder, allMarkets);
}
/**
* @notice Claim all the strike accrued by holder in the specified markets
* @param holder The address to claim STRK for
* @param sTokens The list of markets to claim STRK in
*/
function claimStrike(address holder, SToken[] memory sTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimStrike(holders, sTokens, true, true);
}
/**
* @notice Claim all strike accrued by the holders
* @param holders The addresses to claim STRK for
* @param sTokens The list of markets to claim STRK in
* @param borrowers Whether or not to claim STRK earned by borrowing
* @param suppliers Whether or not to claim STRK earned by supplying
*/
function claimStrike(address[] memory holders, SToken[] memory sTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < sTokens.length; i++) {
SToken sToken = sTokens[i];
require(markets[address(sToken)].isListed, "market must be listed");
if (borrowers) {
Exp memory borrowIndex = Exp({mantissa: sToken.borrowIndex()});
updateStrikeBorrowIndex(address(sToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerStrike(address(sToken), holders[j], borrowIndex);
strikeAccrued[holders[j]] = grantSTRKInternal(holders[j], strikeAccrued[holders[j]]);
}
}
if (suppliers) {
updateStrikeSupplyIndex(address(sToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierStrike(address(sToken), holders[j]);
strikeAccrued[holders[j]] = grantSTRKInternal(holders[j], strikeAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer STRK to the user
* @dev Note: If there is not enough STRK, we do not perform the transfer all.
* @param user The address of the user to transfer STRK to
* @param amount The amount of STRK to (possibly) transfer
* @return The amount of STRK which was NOT transferred to the user
*/
function grantSTRKInternal(address user, uint amount) internal returns (uint) {
STRK strk = STRK(getSTRKAddress());
uint strikeRemaining = strk.balanceOf(address(this));
if (amount > 0 && amount <= strikeRemaining) {
strk.transfer(user, amount);
return 0;
}
return amount;
}
/*** STRK Distribution Admin ***/
/**
* @notice Update additional accrued Strike for a contributor
* @param contributor The address to calculate contributor rewards
*/
function updateContributorRewards(address contributor) public {
uint strikeSpeed = strikeContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && strikeSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, strikeSpeed);
uint contributorAccrued = add_(strikeAccrued[contributor], newAccrued);
strikeAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Set Strike speed for a single contributor
* @param contributor The contributor whose Strike speed to set
* @param strikeSpeed New Strike speed for contributor
*/
function _setContributorStrikeSpeed(address contributor, uint strikeSpeed) public {
require(adminOrInitializing(), "Only Admin can set STRK speed");
// Update contributor STRK reward before update speed
updateContributorRewards(contributor);
if (strikeSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
}
// Update last block
lastContributorBlock[contributor] = getBlockNumber();
// Update STRK speed
strikeContributorSpeeds[contributor] = strikeSpeed;
emit ContributorStrikeSpeedUpdated(contributor, strikeSpeed);
}
/**
* @notice Transfer STRK to the recipient
* @param recipient The address of the receipient to transfer STRK to
* @param amount The amount of STRK to (possibly) transfer
*/
function _grantSTRK(address recipient, uint amount) public {
require(adminOrInitializing(), "Only Admin can grant STRK");
uint amountLeft = grantSTRKInternal(recipient, amount);
require(amountLeft == 0, "Insufficient STRK for grant");
emit StrikeGranted(recipient, amount);
}
/**
* @notice Set the amount of STRK distributed per block
* @param strikeRate_ The amount of STRK wei per block to distribute
*/
function _setStrikeRate(uint strikeRate_) public {
require(adminOrInitializing(), "only admin can change strike rate");
uint oldRate = strikeRate;
strikeRate = strikeRate_;
emit NewStrikeRate(oldRate, strikeRate_);
// refreshStrikeSpeedsInternal();
}
/**
* @notice Remove a market from strikeMarkets, preventing it from earning STRK in the flywheel
* @param sToken The address of the market to drop
*/
function _dropStrikeMarket(address sToken) public {
require(msg.sender == admin, "only admin can drop strike market");
Market storage market = markets[sToken];
require(market.isStriked == true, "market is not a strike market");
market.isStriked = false;
emit MarketStriked(SToken(sToken), false);
// refreshStrikeSpeedsInternal();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (SToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the STRK token
* @return The address of STRK
*/
function getSTRKAddress() public view returns (address) {
return 0x74232704659ef37c08995e386A2E26cc27a8d7B1;
}
}
|
Delegates execution to an implementation contract. It returns to the external caller whatever the implementation returns or forwards reverts./ delegate all other functions to current implementation
|
function () external payable {
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
}
}
| 6,071,405 |
pragma solidity ^0.5.16;
import "./CErc20.sol";
/**
* @title Compound's CErc20Immutable Contract
* @notice CTokens which wrap an EIP-20 underlying and are immutable
* @author Compound
*/
contract CErc20Immutable is CErc20 {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// Initialize the market
initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
|
Accrue interest then return the up-to-date exchange rate return Calculated exchange rate scaled by 1e18/
|
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
| 17,587 |
./partial_match/97/0x9194EAfFDE96b9F6c6169146A177daDE231538a8/sources/ZombieMarket.sol
|
设置战将合约地址(合约拥有者可调) _dragonAddress:战将合约地址/
|
function setDragonAddress(ZombieDragon _dragonAddress) external onlyOwner{
dragonAddress = _dragonAddress;
emit ChangeDragonAddress(_dragonAddress);
}
| 11,348,957 |
pragma solidity ^0.4.13; // указываем версию компилятора
// [email protected]
// Данный контракт создавался для демонстрации студентам BSU Blockchain and Smartcontracts Lab,
// контракт содержит преднамеренные недостатки безопасности и его не желательно использовать
// в production среде.
// Описание GuestBook:
// + Администратор может менять название гостевой книги
// + Зарегистрированный пользователь может добавлять любое сообщение
// + Пользователи могут ставить рейтинг за сообщение
// + Администратор может уничтожить контракт
// + Администратор может удалить сообщение
// + Администратор может удалить сообщение
// + Имеется возможность назначить нового администратора контракта
// + Имеется поиск сообщения по его id
contract GuestBook {
address adminAddress; // адрес администратора
string guestbookName; // название гостевой книги
// структура хранимых сообщений
struct notarizedMessage {
bytes32 message; // рейтинг сообщения
int rating; // рейтинг сообщения
uint timeStamp; // временная метка добавления сообщения в GuestBook
}
// структура хранимых данных пользователей GuestBook
struct User {
string nickname; // имя пользователя
bytes32 city; // город проживания пользователя
bytes32 country; // страна проживания пользователя
bytes32 email; // email пользователя
bytes32[] myMessages; // список хранимых сообщений пользователя
}
mapping ( uint => notarizedMessage) notarizedMessages; // позволяет отображать данные сообщения по его тексту
bytes32[] userMessages; // список всех сообщений пользователей
mapping ( address => User ) Users; // позволяет отображать данные пользователя по его адресу
address[] usersByAddress; // массив всех зарегистрированных пользователей в GuestBook
uint constant public config_price = 10 finney; // стоимость повышения рейтинга сообщения
uint messageId = 0; // идентификатор сообщения
// события для мониторинга
event registered(string _nickname, address _addr);
// это конструктор, он имеет тоже наименование, что и контракт. Он получает вызов однажды при развёртывании контракта
function GuestBook() {
adminAddress = msg.sender; // устанавливаем администратора, чтобы он мог удалить плохих пользователей, если это необходимо
}
modifier onlyAdmin() {
if (msg.sender != adminAddress) revert(); // если отправитель не является администратором, то вызываем исключение
_;
}
// удаляем существующего пользователя из GuestBook. Только администратор может осуществить данное действие
function removeUser(address _badUser) onlyAdmin returns (bool success) {
delete Users[_badUser];
return true;
}
// удаляем существующее сообщение из GuestBook. Только администратор может осуществить данное действие
function removeMessage(uint _badIdMessage) onlyAdmin returns (bool success) {
delete notarizedMessages[_badIdMessage];
return true;
}
// регистрируем нового пользователя
function registerNewUser(string nickname, bytes32 city, bytes32 email, bytes32 country) returns (bool success) {
address thisNewAddress = msg.sender;
// необходима проверка существующих вводных данных от внешнего пользователя. Например был ли никнейм null или существовал ли пользователь с таким псевдонимом
if(bytes(Users[msg.sender].nickname).length != 0) revert(); // проверяем наличия существования пользователя
if(bytes(nickname).length == 0) revert(); // проверяем наличие указанного nickname пользователя для регистрации
Users[thisNewAddress].nickname = nickname;
Users[thisNewAddress].city = city;
Users[thisNewAddress].email = email;
Users[thisNewAddress].country = country;
usersByAddress.push(thisNewAddress); // добавляем в список нового пользователя
registered(nickname, thisNewAddress); // обращаемся к событию
return true;
}
// метод позволяющий добавить пользователю новое сообщение.
function addMessageFromUser(bytes32 _userMessage) returns (bool success)
{
address thisNewAddress = msg.sender;
if(bytes(Users[thisNewAddress].nickname).length == 0) revert();// убеждаемся что пользователь зарегистрирован в GuestBook
if(_userMessage.length == 0) revert(); // проверяем наличие сообщения
messageId++; // увеличиваем на один идентификатор сообщения
// проверяем наличие существующего сообщения в списке всех сообщений
// Вопрос: почему очень нежелательно использовать следующий цикл? К чему это может привести?
bool message_found = false;
for(uint i = 0; i < userMessages.length; i++)
{
if(userMessages[i] == _userMessage) {
message_found = true; // найдено хоть одно точно такое же сообщение
break;
}
}
if (message_found == false) userMessages.push(_userMessage); // добавляем в общий список сообщение пользователя
notarizedMessages[messageId].rating = 0;
notarizedMessages[messageId].message = _userMessage;
notarizedMessages[messageId].timeStamp = block.timestamp; // устанавливаем метку времени создания сообщения
Users[thisNewAddress].myMessages.push(_userMessage); // добавляем сообщение в список сообщений пользователя
return true;
}
// возвращаем список всех зарегистрированных пользователей
function getUsers() constant returns (address[]) {
return usersByAddress;
}
// возвращаем данные зарегистрированного пользователя
function getUser(address userAddress) constant returns (string, bytes32, bytes32, bytes32, bytes32[]) {
return (
Users[userAddress].nickname,
Users[userAddress].city,
Users[userAddress].email,
Users[userAddress].country,
Users[userAddress].myMessages
);
}
// возвращаем список всех сообщений
function getAllMessages() constant returns (bytes32[]) {
return userMessages;
}
// возвращаем список сообщений пользователя
function getUserMessages(address userAddress) constant returns (bytes32[]) {
return Users[userAddress].myMessages;
}
// получаем данные о сообщении отправив его идентификатор
function getMessage(uint _messageId) constant returns (bytes32, int, uint)
{
return (
notarizedMessages[_messageId].message,
notarizedMessages[_messageId].rating,
notarizedMessages[_messageId].timeStamp
);
}
// увеличиваем рейтинг сообщения пользователя
function changeMessageRating(uint _messageId, bytes32 _vector) payable returns (bool success) {
if (_vector != "higher" || _vector != "lower") revert(); // если пользователь не указал вектор рейтинга.
if (notarizedMessages[_messageId].timeStamp == 0) revert(); // если идентификатор сообщения не существует. Способ определения наличия ключа https://goo.gl/uDfYJx
if (msg.value != config_price) revert(); //если пользователь не отправил необходимую сумму сердств на повышение рейтинга
if (_vector == "higher") {
notarizedMessages[messageId].rating = notarizedMessages[messageId].rating++; // увеличиваем рейтинг сообщения на один
}
if (_vector == "lower") {
notarizedMessages[messageId].rating = notarizedMessages[messageId].rating--; // уменьшаем рейтинг сообщения на один
}
return true;
}
// меняем администратора GuestBook
function changeAdmin(address newAdminAddress) onlyAdmin returns (bool success) {
if(bytes(Users[newAdminAddress].nickname).length == 0) revert(); // убеждаемся что пользователь зарегистрирован в GuestBook
adminAddress = newAdminAddress;
return true;
}
// меняем название гостевой книги
function changeGuestBookName(string newGuestBookName) onlyAdmin {
guestbookName = newGuestBookName;
}
// уничтожаем контракт
function killContract() onlyAdmin {
selfdestruct(adminAddress);
}
}
|
удаляем существующего пользователя из GuestBook. Только администратор может осуществить данное действие
|
function removeUser(address _badUser) onlyAdmin returns (bool success) {
delete Users[_badUser];
return true;
}
| 14,034,805 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./Token.sol";
contract dBank {
//assign Token contract to variable\
Token private token;
//add mappings
mapping(address => uint) public etherBalanceOf;
mapping(address => uint) public depositStart;
mapping(address => uint) public collateralEther;
mapping(address => bool) public isDeposited;
mapping(address => bool) public isBorrowed;
//add events
event Deposit(address indexed user, uint etherAmount, uint timeStart);
event Withdraw(address indexed user, uint etherAmount, uint depositTime, uint interest);
event Borrow(address indexed user, uint collateralEtherAmount, uint borrowedTokenAmount);
event PayOff(address indexed user, uint fee);
//pass as constructor argument deployed Token contract
constructor(Token _token) public {
token = _token;
//assign token deployed contract to variable
}
function deposit() payable public {
//check if msg.sender didn't already deposited funds
//check if msg.value is >= than 0.01 ETH
require(isDeposited[msg.sender] == false, 'Error, deposit already active');
require(msg.value>=1e16, 'Error, deposit must be >= 0.01 ETH');
etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] + msg.value;
depositStart[msg.sender] = depositStart[msg.sender] + block.timestamp;
//increase msg.sender ether deposit balance
//start msg.sender hodling time
//set msg.sender deposit status to true
//emit Deposit event
isDeposited[msg.sender] = true;
emit Deposit(msg.sender, msg.value, block.timestamp);
}
function withdraw() public {
require(isDeposited[msg.sender]== true, 'Error, no previous deposit');
uint userBalance = etherBalanceOf[msg.sender];
//check if msg.sender deposit status is true
//assign msg.sender ether deposit balance to variable for event
//check user's hodl time
uint depositTime = block.timestamp - depositStart[msg.sender];
//calc interest per second
uint interestPerSecond = 31668017 * (etherBalanceOf[msg.sender] / 1e16);
uint interest = interestPerSecond * depositTime;
//calc accrued interest
//send eth to user
payable(msg.sender).transfer(userBalance);
//send interest in tokens to user
token.mint(msg.sender, interest);
//reset depositer data
depositStart[msg.sender] = 0;
etherBalanceOf[msg.sender] = 0;
isDeposited[msg.sender] = false;
//emit event
emit Withdraw(msg.sender, userBalance, depositTime, interest);
}
function borrow() payable public {
//check if collateral is >= than 0.01 ETH
require(msg.value>=1e16, 'Error, collateral must be >= 0.01 ETH');
//check if user doesn't have active loan
require(isBorrowed[msg.sender] == false, 'Error, loan already taken');
//thus Ether will be locked till user payOff the loan
collateralEther[msg.sender] = collateralEther[msg.sender] + msg.value;
//calc tokens amount to mint, 50% of msg.value
uint tokensToMint = collateralEther[msg.sender] * 4500;
//mint&send tokens to user
token.mint(msg.sender, tokensToMint);
//activate borrower's loan status
isBorrowed[msg.sender] = true;
//emit event
emit Borrow(msg.sender, collateralEther[msg.sender], tokensToMint);
}
function payOff() public {
//check if loan is active
require(isBorrowed[msg.sender] == true, 'Error, loa not active');
//transfer tokens from user back to the contract
require(token.transferFrom(msg.sender, address(this), collateralEther[msg.sender]*4500), "Error, can't receive tokens"); //must approve dBank 1st
//calc 10$ fee
uint fee = collateralEther[msg.sender]/10;
//send user's collateral minus fee
payable(msg.sender).transfer(collateralEther[msg.sender]-fee);
//reset borrower's data
collateralEther[msg.sender] = 0;
isBorrowed[msg.sender] = false;
//emit event
emit PayOff(msg.sender, fee);
}
}
|
check if loan is activetransfer tokens from user back to the contractcalc 10$ feesend user's collateral minus feereset borrower's dataemit event
|
function payOff() public {
require(isBorrowed[msg.sender] == true, 'Error, loa not active');
uint fee = collateralEther[msg.sender]/10;
payable(msg.sender).transfer(collateralEther[msg.sender]-fee);
collateralEther[msg.sender] = 0;
isBorrowed[msg.sender] = false;
emit PayOff(msg.sender, fee);
}
| 5,385,050 |
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/contracts/collateral/Collateral.sol
|
Injects additional collateral into a product to resolve shortfall Shortfall is a measure of settled insolvency in the market This hook can be used by the product owner or an insurance fund to re-capitalize an insolvent market product Product to resolve shortfall for amount Amount of shortfall to resolve/
|
function resolveShortfall(IProduct product, UFixed18 amount) external isProduct(product) notPaused {
_products[product].resolve(amount);
token.pull(msg.sender, amount);
emit ShortfallResolution(product, amount);
}
| 1,912,782 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "../../libraries/SafeMathExt.sol";
import "../../interface/IOracle.sol";
// An oracle router calculates the asset price with a given path.
// A path is [(oracle, isInverse)]. The OracleRouter never verifies whether the path is reasonable.
// collateral() and underlyingAsset() only shows correct value if the collateral token is in the 1st item
// and the underlying asset is always in the last item.
//
// Example 1: underlying = eth, collateral = usd, oracle1 = eth/usd = 1000
// [(oracle1, false)], return oracle1 = 1000
//
// Example 2: underlying = usd, collateral = eth, oracle1 = eth/usd
// [(oracle1, true)], return (1 / oracle1) = 0.001
//
// Example 3: underlying = btc, collateral = eth, oracle1 = btc/usd = 10000, oracle2 = eth/usd = 1000
// [(oracle2, true), (oracle1, false)], return (1 / oracle2) * oracle1 = 10
//
// Example 4: underlying = eth, collateral = btc, oracle1 = btc/usd = 10000, oracle2 = usd/eth = 0.001
// [(oracle1, true), (oracle2, true)], return (1 / oracle1) * (1 / oracle2) = 0.1
//
// Example 5: underlying = xxx, collateral = eth, oracle1 = btc/usd = 10000, oracle2 = eth/usd = 1000, oracle3 = xxx/btc = 2
// [(oracle2, true), (oracle1, false), (oracle3, false)], return (1 / oracle2) * oracle1 * oracle3 = 20
//
contract OracleRouter {
using SafeMathExt for int256;
using SafeMathExt for uint256;
struct Route {
address oracle;
bool isInverse;
}
struct RouteDump {
address oracle;
bool isInverse;
string underlyingAsset;
string collateral;
}
string public constant source = "OracleRouter";
Route[] internal _path;
constructor(Route[] memory path_) {
require(path_.length > 0, "empty path");
for (uint256 i = 0; i < path_.length; i++) {
require(path_[i].oracle != address(0), "empty oracle");
_path.push(Route({ oracle: path_[i].oracle, isInverse: path_[i].isInverse }));
}
}
/**
* @dev Get collateral symbol.
*
* The OracleRouter never verifies whether the path is reasonable.
* collateral() and underlyingAsset() only shows correct value if the collateral token is in
* the 1st item and the underlying asset is always in the last item.
* @return symbol string
*/
function collateral() public view returns (string memory) {
if (_path[0].isInverse) {
return IOracle(_path[0].oracle).underlyingAsset();
} else {
return IOracle(_path[0].oracle).collateral();
}
}
/**
* @dev Get underlying asset symbol.
*
* The OracleRouter never verifies whether the path is reasonable.
* collateral() and underlyingAsset() only shows correct value if the collateral token is in
* the 1st item and the underlying asset is always in the last item.
* @return symbol string
*/
function underlyingAsset() public view returns (string memory) {
uint256 i = _path.length - 1;
if (_path[i].isInverse) {
return IOracle(_path[i].oracle).collateral();
} else {
return IOracle(_path[i].oracle).underlyingAsset();
}
}
/**
* @dev Mark price.
*/
function priceTWAPLong() external returns (int256 newPrice, uint256 newTimestamp) {
newPrice = Constant.SIGNED_ONE;
for (uint256 i = 0; i < _path.length; i++) {
(int256 p, uint256 t) = IOracle(_path[i].oracle).priceTWAPLong();
if (_path[i].isInverse && p != 0) {
p = Constant.SIGNED_ONE.wdiv(p);
}
newPrice = newPrice.wmul(p);
newTimestamp = newTimestamp.max(t);
}
}
/**
* @dev Index price.
*/
function priceTWAPShort() external returns (int256 newPrice, uint256 newTimestamp) {
newPrice = Constant.SIGNED_ONE;
for (uint256 i = 0; i < _path.length; i++) {
(int256 p, uint256 t) = IOracle(_path[i].oracle).priceTWAPShort();
if (_path[i].isInverse && p != 0) {
p = Constant.SIGNED_ONE.wdiv(p);
}
newPrice = newPrice.wmul(p);
newTimestamp = newTimestamp.max(t);
}
}
/**
* @dev The market is closed if the market is not in its regular trading period.
*/
function isMarketClosed() external returns (bool) {
for (uint256 i = 0; i < _path.length; i++) {
if (IOracle(_path[i].oracle).isMarketClosed()) {
return true;
}
}
return false;
}
/**
* @dev The oracle service was shutdown and never online again.
*/
function isTerminated() external returns (bool) {
for (uint256 i = 0; i < _path.length; i++) {
if (IOracle(_path[i].oracle).isTerminated()) {
return true;
}
}
return false;
}
/**
* @dev Dump the addresses
*/
function getPath() external view returns (Route[] memory) {
return _path;
}
/**
* @dev Dump the path with info
*/
function dumpPath() external view returns (RouteDump[] memory) {
RouteDump[] memory ret = new RouteDump[](_path.length);
for (uint256 i = 0; i < _path.length; i++) {
ret[i].oracle = _path[i].oracle;
ret[i].isInverse = _path[i].isInverse;
ret[i].underlyingAsset = IOracle(_path[i].oracle).underlyingAsset();
ret[i].collateral = IOracle(_path[i].oracle).collateral();
}
return ret;
}
}
|
Dump the path with info/
|
function dumpPath() external view returns (RouteDump[] memory) {
RouteDump[] memory ret = new RouteDump[](_path.length);
for (uint256 i = 0; i < _path.length; i++) {
ret[i].oracle = _path[i].oracle;
ret[i].isInverse = _path[i].isInverse;
ret[i].underlyingAsset = IOracle(_path[i].oracle).underlyingAsset();
ret[i].collateral = IOracle(_path[i].oracle).collateral();
}
return ret;
}
| 12,599,369 |
pragma solidity ^0.5.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Context {
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 Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function 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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ICurveFi {
function exchange(
int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount
) external;
}
interface yERC20 {
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getPricePerFullShare() external view returns (uint256);
}
interface iBorrower {
function borrowAave(address _reserve, uint256 _amount) external;
function getBorrowDebt(address _reserve) external view returns (uint256);
function getBorrowInterest(address _reserve) external view returns (uint256);
function repayAave(address _reserve, uint256 _amount) external;
function getYToken(address _reserve) external view returns (address);
function getCurveID(address _reserve) external view returns (uint8);
function isLeverage(uint256 leverage) external view returns (bool);
function isReserve(address _reserve) external view returns (bool);
}
interface iLedger {
function mintDebt(address _reserve, address account, uint256 amount) external;
function burnDebt(address _reserve, address account, uint256 amount) external;
function mintPrincipal(address _reserve, address account, uint256 amount) external;
function burnPrincipal(address _reserve, address account, uint256 amount) external;
function mintPosition(address _reserve, address account, uint256 amount) external;
function burnPosition(address _reserve, address account, uint256 amount) external;
function getUserInterest(address _reserve, address _user) external view returns (uint256);
function getUserDebt(address _reserve, address _user) external view returns (uint256);
function getDebt(address _reserve, address _user) external view returns (uint256);
function getPosition(address _reserve, address _user) external view returns (uint256);
function getPrincipal(address _reserve, address _user) external view returns (uint256);
function getTotalDebt(address _reserve) external view returns (uint256);
function getTotalPosition(address _user) external view returns (uint256);
function getTotalPrincipal(address _user) external view returns (uint256);
function isSafe(address _user) external view returns (bool);
}
contract iTrade is ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant yCurveSwap = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
address public constant yDAI = address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01);
address public constant yUSDC = address(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e);
address public constant yUSDT = address(0x83f798e925BcD4017Eb265844FDDAbb448f1707D);
address public constant yTUSD = address(0x73a052500105205d34Daf004eAb301916DA8190f);
address public constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address public constant USDT = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address public constant TUSD = address(0x0000000000085d4780B73119b644AE5ecd22b376);
iBorrower public collateral;
iLedger public ledger;
constructor() public {
collateral = iBorrower(0xaCD746993f60e807fBf69F646e42DaedA63a4CfC);
ledger = iLedger(0xaCD746993f60e807fBf69F646e42DaedA63a4CfC);
approveToken();
}
function setCollateral(iBorrower _collateral) external onlyOwner {
collateral = iBorrower(_collateral);
}
function setLedger(iLedger _ledger) external onlyOwner {
ledger = iLedger(_ledger);
}
function approveToken() public {
IERC20(DAI).safeApprove(address(collateral), uint(-1));
IERC20(USDC).safeApprove(address(collateral), uint(-1));
IERC20(TUSD).safeApprove(address(collateral), uint(-1));
IERC20(USDT).safeApprove(address(collateral), uint(0));
IERC20(USDT).safeApprove(address(collateral), uint(-1));
IERC20(DAI).safeApprove(yDAI, uint(-1));
IERC20(USDC).safeApprove(yUSDC, uint(-1));
IERC20(TUSD).safeApprove(yTUSD, uint(-1));
IERC20(USDT).safeApprove(yUSDT, uint(0));
IERC20(USDT).safeApprove(yUSDT, uint(-1));
// Approvals for swaps
IERC20(DAI).safeApprove(yCurveSwap, uint(-1));
IERC20(USDC).safeApprove(yCurveSwap, uint(-1));
IERC20(TUSD).safeApprove(yCurveSwap, uint(-1));
IERC20(USDT).safeApprove(yCurveSwap, uint(0));
IERC20(USDT).safeApprove(yCurveSwap, uint(-1));
}
function addCollateral(address _reserve, address _to, uint256 _amount, uint256 _min_to_amount, uint256 leverage) external nonReentrant {
addCollateralWithFee(_reserve, _to, _amount, _min_to_amount, leverage, 0);
}
struct AddCollateralLocalVars {
uint256 _yTokenBefore;
uint256 _yTokenAfter;
uint256 _toSell;
uint8 _fromID;
uint8 _toID;
uint256 _toPrice;
uint256 _toYtoken;
uint256 _boughtBefore;
uint256 _boughtAfter;
uint256 _bought;
uint256 _boughtUnderlying;
}
function addCollateralWithFee(address _reserve, address _to, uint256 _amount, uint256 _min_to_amount, uint256 leverage, uint256 fee) public nonReentrant {
require(collateral.isLeverage(leverage) == true, "itrade: invalid leverage parameter");
require(collateral.isReserve(_reserve) == true, "itrade: invalid reserve");
IERC20(_reserve).safeTransferFrom(msg.sender, address(this), _amount.add(fee));
ledger.mintPrincipal(_reserve, msg.sender, _amount);
yERC20(collateral.getYToken(_reserve)).deposit(_amount.add(fee));
uint256 _borrow = _amount.mul(leverage);
uint256 _pool = collateral.getBorrowDebt(_reserve);
uint256 _debt = 0;
if (_pool == 0) {
_debt = _borrow;
} else {
_debt = (_borrow.mul(ledger.getTotalDebt(_reserve))).div(_pool);
}
ledger.mintDebt(_reserve, msg.sender, _debt);
collateral.borrowAave(_reserve, _borrow);
AddCollateralLocalVars memory vars;
vars._yTokenBefore = IERC20(collateral.getYToken(_reserve)).balanceOf(address(this));
yERC20(collateral.getYToken(_reserve)).deposit(_borrow);
vars._yTokenAfter = IERC20(collateral.getYToken(_reserve)).balanceOf(address(this));
vars._toSell = vars._yTokenAfter.sub(vars._yTokenBefore);
vars._fromID = collateral.getCurveID(_reserve);
vars._toID = collateral.getCurveID(_to);
vars._toPrice = yERC20(collateral.getYToken(_to)).getPricePerFullShare();
vars._toYtoken = _min_to_amount.mul(1e18).div(vars._toPrice).add(1);
vars._boughtBefore = IERC20(collateral.getYToken(_to)).balanceOf(address(this));
ICurveFi(yCurveSwap).exchange(vars._fromID, vars._toID, vars._toSell, vars._toYtoken);
vars._boughtAfter = IERC20(collateral.getYToken(_to)).balanceOf(address(this));
vars._bought = vars._boughtAfter.sub(vars._boughtBefore);
vars._boughtUnderlying = vars._bought.mul(vars._toPrice).div(1e18);
ledger.mintPosition(_to, msg.sender, vars._boughtUnderlying);
require(vars._boughtUnderlying >= _min_to_amount, "itrade: underlying slippage");
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
function withdrawCollateral(address _reserve, uint256 _amount) public nonReentrant {
require(collateral.isReserve(_reserve) == true, "itrade: invalid reserve");
require(ledger.getUserDebt(_reserve, msg.sender) == 0, "itrade: outstanding debt to settle");
require(_amount <= ledger.getPrincipal(_reserve, msg.sender), "itrade: insufficient balance");
require(IERC20(_reserve).balanceOf(address(this)) == 0, "itrade: unexpected result");
uint256 _price = yERC20(collateral.getYToken(_reserve)).getPricePerFullShare();
uint256 _ytoken = _amount.mul(1e18).div(_price);
yERC20(collateral.getYToken(_reserve)).withdraw(_ytoken);
require(IERC20(_reserve).balanceOf(address(this)) >= _amount, "itrade: unexpected result");
ledger.burnPrincipal(_reserve, msg.sender, _amount);
IERC20(_reserve).safeTransfer(msg.sender, _amount);
// Cleanup dust (if any)
if (IERC20(_reserve).balanceOf(address(this)) > 0) {
yERC20(collateral.getYToken(_reserve)).deposit(IERC20(_reserve).balanceOf(address(this)));
}
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
function repayDebtFor(address _reserve, address _user, uint256 _amount) public nonReentrant {
require(collateral.isReserve(_reserve) == true, "itrade: invalid reserve");
uint256 debt = ledger.getUserDebt(_reserve, _user);
if (_amount > debt) {
_amount = debt;
}
IERC20(_reserve).safeTransferFrom(msg.sender, address(this), _amount);
uint256 shares = ledger.getDebt(_reserve, _user).mul(_amount).div(debt);
collateral.repayAave(_reserve, _amount);
ledger.burnDebt(_reserve, _user, shares);
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
function repayDebt(address _reserve, uint256 _amount) public nonReentrant {
repayDebtFor(_reserve, msg.sender, _amount);
}
function exit(address _reserve) external nonReentrant {
closePosition(_reserve, ledger.getPosition(_reserve,msg.sender));
settle(_reserve);
withdrawCollateral(_reserve, ledger.getPrincipal(_reserve,msg.sender));
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
function settle(address _reserve) public nonReentrant {
require(collateral.isReserve(_reserve) == true, "itrade: invalid reserve");
// TODO: Add in clean principal if any for reserve
uint256 _debt = ledger.getUserDebt(_reserve, msg.sender);
if (_debt > 0) {
IERC20(_reserve).safeTransferFrom(msg.sender, address(this), _debt);
collateral.repayAave(_reserve, _debt);
ledger.burnDebt(_reserve, msg.sender, ledger.getDebt(_reserve,msg.sender));
}
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
struct TradePositionLocalVars {
uint256 _fromPrice;
uint256 _fromYtoken;
uint256 _toPrice;
uint256 _toYtoken;
uint8 _fromID;
uint8 _toID;
uint256 _boughtBefore;
uint256 _soldBefore;
uint256 _boughtAfter;
uint256 _soldAfter;
uint256 _bought;
uint256 _sold;
uint256 _boughtUnderlying;
uint256 _soldUnderlying;
}
// Change trade position to use yTokens instead (to avoid locked up underlying collateral)
function tradePosition(address _reserve, address _to, uint256 _amount, uint256 _min_to_amount) external nonReentrant {
require(collateral.isReserve(_reserve) == true, "itrade: invalid reserve");
require(_amount <= ledger.getPosition(_reserve, msg.sender), "itrade: insufficient balance");
TradePositionLocalVars memory vars;
vars._fromPrice = yERC20(collateral.getYToken(_reserve)).getPricePerFullShare();
vars._fromYtoken = _amount.mul(1e18).div(vars._fromPrice).add(1);
vars._toPrice = yERC20(collateral.getYToken(_to)).getPricePerFullShare();
vars._toYtoken = _min_to_amount.mul(1e18).div(vars._toPrice).add(1);
vars._fromID = collateral.getCurveID(_reserve);
vars._toID = collateral.getCurveID(_to);
vars._boughtBefore = IERC20(collateral.getYToken(_to)).balanceOf(address(this));
vars._soldBefore = IERC20(collateral.getYToken(_reserve)).balanceOf(address(this));
ICurveFi(yCurveSwap).exchange(vars._fromID, vars._toID, vars._fromYtoken, vars._toYtoken);
vars._boughtAfter = IERC20(collateral.getYToken(_to)).balanceOf(address(this));
vars._soldAfter = IERC20(collateral.getYToken(_reserve)).balanceOf(address(this));
vars._bought = vars._boughtAfter.sub(vars._boughtBefore);
vars._sold = vars._soldBefore.sub(vars._soldAfter);
vars._boughtUnderlying = vars._bought.mul(vars._toPrice).div(1e18);
vars._soldUnderlying = vars._sold.mul(vars._fromPrice).div(1e18);
require(vars._soldUnderlying <= _amount, "itrade: sold more than expected");
require(vars._boughtUnderlying >= _min_to_amount, "itrade: underlying slippage");
ledger.burnPosition(_reserve, msg.sender, vars._soldUnderlying);
ledger.mintPosition(_to, msg.sender, vars._boughtUnderlying);
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
function closePosition(address _reserve, uint256 _amount) public nonReentrant {
require(collateral.isReserve(_reserve) == true, "itrade: invalid reserve");
require(_amount <= ledger.getPosition(_reserve,msg.sender), "itrade: insufficient balance");
require(IERC20(_reserve).balanceOf(address(this)) == 0, "itrade: unexpected result");
uint256 debt = ledger.getUserDebt(_reserve, msg.sender);
uint256 ret = 0;
if (_amount > debt) {
ret = _amount.sub(debt);
_amount = debt;
}
uint256 _price = yERC20(collateral.getYToken(_reserve)).getPricePerFullShare();
uint256 _ytoken = _amount.mul(1e18).div(_price).add(1);
yERC20(collateral.getYToken(_reserve)).withdraw(_ytoken);
if (debt > 0) {
uint256 shares = ledger.getDebt(_reserve,msg.sender).mul(_amount).div(debt);
collateral.repayAave(_reserve, _amount);
ledger.burnDebt(_reserve, msg.sender, shares);
}
// Profits from trade
if (ret > 0) {
IERC20(_reserve).safeTransfer(msg.sender, ret);
}
ledger.burnPosition(_reserve, msg.sender, _amount);
// Cleanup dust (if any)
if (IERC20(_reserve).balanceOf(address(this)) > 0) {
yERC20(collateral.getYToken(_reserve)).deposit(IERC20(_reserve).balanceOf(address(this)));
}
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
function seize(address _user) external nonReentrant {
require(ledger.isSafe(_user) == false, "itrade: account is safe");
_seizeReserve(DAI, _user);
_seizeReserve(USDC, _user);
_seizeReserve(USDT, _user);
_seizeReserve(TUSD, _user);
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
require(ledger.isSafe(_user) == true, "itrade: account would liquidate");
}
function _seizeReserve(address _reserve, address _user) internal {
uint256 _principal = ledger.getPrincipal(_reserve,_user);
if (_principal > 0) {
uint256 _debt = ledger.getDebt(_reserve,_user);
uint256 _position = ledger.getPosition(_reserve,_user);
ledger.mintPrincipal(_reserve, _user, _principal);
ledger.burnDebt(_reserve, _user, _debt);
ledger.burnPosition(_reserve, _user, _position);
ledger.mintPrincipal(_reserve, msg.sender, _principal);
ledger.mintDebt(_reserve, msg.sender, _debt);
ledger.mintPosition(_reserve, msg.sender, _position);
}
}
// incase of half-way error
function inCaseTokenGetsStuck(IERC20 _TokenAddress) onlyOwner public {
uint qty = _TokenAddress.balanceOf(address(this));
_TokenAddress.safeTransfer(msg.sender, qty);
}
// incase of half-way error
function inCaseTokenGetsStuckPartial(IERC20 _TokenAddress, uint256 _amount) onlyOwner public {
_TokenAddress.safeTransfer(msg.sender, _amount);
}
// incase of half-way error
function inCaseETHGetsStuck() onlyOwner public{
(bool result, ) = msg.sender.call.value(address(this).balance)("");
require(result, "transfer of ETH failed");
}
}
|
Profits from trade Cleanup dust (if any)
|
function closePosition(address _reserve, uint256 _amount) public nonReentrant {
require(collateral.isReserve(_reserve) == true, "itrade: invalid reserve");
require(_amount <= ledger.getPosition(_reserve,msg.sender), "itrade: insufficient balance");
require(IERC20(_reserve).balanceOf(address(this)) == 0, "itrade: unexpected result");
uint256 debt = ledger.getUserDebt(_reserve, msg.sender);
uint256 ret = 0;
if (_amount > debt) {
ret = _amount.sub(debt);
_amount = debt;
}
uint256 _price = yERC20(collateral.getYToken(_reserve)).getPricePerFullShare();
uint256 _ytoken = _amount.mul(1e18).div(_price).add(1);
yERC20(collateral.getYToken(_reserve)).withdraw(_ytoken);
if (debt > 0) {
uint256 shares = ledger.getDebt(_reserve,msg.sender).mul(_amount).div(debt);
collateral.repayAave(_reserve, _amount);
ledger.burnDebt(_reserve, msg.sender, shares);
}
if (ret > 0) {
IERC20(_reserve).safeTransfer(msg.sender, ret);
}
ledger.burnPosition(_reserve, msg.sender, _amount);
if (IERC20(_reserve).balanceOf(address(this)) > 0) {
yERC20(collateral.getYToken(_reserve)).deposit(IERC20(_reserve).balanceOf(address(this)));
}
require(ledger.isSafe(msg.sender) == true, "itrade: account would liquidate");
}
| 12,622,795 |
./partial_match/1/0x76E1DeB20301b710aC6252ce4f95F9Cc0ac17808/sources/TokenSpring.sol
|
Update lockedTokens amount before using it in computations after.updateAccounting();
|
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'TokenSpring: reached maximum unlock schedules');
unlockTokens();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'TokenSpring: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
| 4,456,953 |
./full_match/42/0x68A37709Ed125aDB3Cf76223eb88d0769400dA45/sources/contracts/MainContract.sol
|
This function executes a drop. During the execution all joined users get their previously specificed number of NFTs randomly assigned. To make sure no NFT gets assigned to multiple users, it is removed from the list of available NFTs. loop trough the number of NFTs j reserved by user i
|
function drop(uint256 _dropHash) public {
require(
nftOwnerships[_dropHash][0].dropTime <= block.timestamp,
"Droptime not yet reached!"
);
for (uint256 i = 0; i < joinedUsers[_dropHash].length; i++) {
shuffle(_dropHash);
for (
uint256 j = 0;
j < nftReservations[joinedUsers[_dropHash][i]][_dropHash];
j++
) {
uint256 nftElement = getNFTIndex(
availableNFTs[_dropHash][j],
_dropHash
);
nftOwnerships[_dropHash][nftElement].reservedFor = joinedUsers[
_dropHash
][i];
nftOwnerships[_dropHash][nftElement].reservedUntil =
nftOwnerships[_dropHash][nftElement]
.reservationTimeoutSeconds +
block.timestamp;
nftReservationInformationOfUsers[joinedUsers[_dropHash][i]][
_dropHash
].push(nftOwnerships[_dropHash][nftElement].uri);
remove(j, _dropHash);
}
}
}
| 9,580,565 |
./full_match/1/0xeA944E90ea6faF29C136c43026fF8A9e0fBF68C9/sources/browser/oldtoken.sol
|
Sets an address frozen status for this token. addr The address for which to update frozen status freeze Frozen status of the address/
|
function setAddressFrozen(address addr, bool freeze) public onlyAgent {
frozen[addr] = freeze;
emit AddressFrozen(addr, freeze, msg.sender);
}
| 4,977,758 |
pragma solidity ^0.4.4;
contract Voting {
mapping (bytes32 => uint8) public votesReceived;
// 存储候选人名字的数组
bytes32[] public candidateList;
function Voting(bytes32[] candidateNames) public {
candidateList = candidateNames;
}
function totalVotesFor(bytes32 candidate) public constant returns (uint8) {
//require(validCandidate(candidate) == true);
if (validCandidate(candidate) == true) {
return votesReceived[candidate];
} else {
return 0;
}
}
function voteForCandidate(bytes32 candidate) public {
//assert(validCandidate(candidate) == true);
if (validCandidate(candidate) == true) {
votesReceived[candidate] += 1;
Voted(bytes32ToString(candidate));
}
}
function validCandidate(bytes32 candidate) public constant returns (bool) {
for (uint i = 0; i < candidateList.length; i++) {
if (candidateList[i]==candidate) {
return true;
}
}
return false;
}
function bytes32ToString(bytes32 x) constant returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
event Voted(string candidate);
}
|
require(validCandidate(candidate) == true);
|
function totalVotesFor(bytes32 candidate) public constant returns (uint8) {
if (validCandidate(candidate) == true) {
return votesReceived[candidate];
return 0;
}
}
| 989,144 |
./full_match/5/0xfAe93901d38CE9A2F6A14F21d731826F32dE30B9/sources/contracts/Controller.sol
|
Setter for DAO address _dao DAO address
|
function setDao(address _dao) external onlyDao {
dao = _dao;
}
| 1,903,031 |
./full_match/42161/0x4829022F8BAC287813d24e5d00C8B31Fa3b42c8b/sources/contracts/MonkeyBuilder.sol
|
Collects and distributes the primary sale value of tokens being claimed.
|
function _collectPriceOnClaim(
address _primarySaleRecipient,
uint256 _quantityToClaim,
address _currency,
uint256 _pricePerToken
) internal virtual {
if (_pricePerToken == 0) {
return;
}
uint256 totalPrice = _quantityToClaim * _pricePerToken;
require(totalPrice > 0, "quantity too low");
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == totalPrice, "Must send total price.");
}
address saleRecipient = _primarySaleRecipient;
CurrencyTransferLib.transferCurrency(
_currency,
msg.sender,
saleRecipient,
totalPrice
);
}
| 16,297,974 |
./full_match/1/0xa145eCA55AE0E39D7c228ed7A962424a97AC74cB/sources/browser/ExchangePortal.sol
|
Transfers tokens to this contract and approves them to another address _source Token to transfer and approve _sourceAmount The amount to transfer and approve (in _source token) _to Address to approve to/
|
function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private {
require(_source.transferFrom(msg.sender, address(this), _sourceAmount));
_source.approve(_to, _sourceAmount);
}
| 3,183,959 |
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2021 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.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../../external/ILiquidityProviderSandbox.sol";
import "../../fixins/FixinCommon.sol";
import "../../fixins/FixinEIP712.sol";
import "../../migrations/LibMigrate.sol";
import "../interfaces/IFeature.sol";
import "../interfaces/IMultiplexFeature.sol";
import "./MultiplexLiquidityProvider.sol";
import "./MultiplexOtc.sol";
import "./MultiplexRfq.sol";
import "./MultiplexTransformERC20.sol";
import "./MultiplexUniswapV2.sol";
import "./MultiplexUniswapV3.sol";
/// @dev This feature enables efficient batch and multi-hop trades
/// using different liquidity sources.
contract MultiplexFeature is
IFeature,
IMultiplexFeature,
FixinCommon,
MultiplexLiquidityProvider,
MultiplexOtc,
MultiplexRfq,
MultiplexTransformERC20,
MultiplexUniswapV2,
MultiplexUniswapV3
{
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "MultiplexFeature";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(2, 0, 0);
/// @dev The highest bit of a uint256 value.
uint256 private constant HIGH_BIT = 2 ** 255;
/// @dev Mask of the lower 255 bits of a uint256 value.
uint256 private constant LOWER_255_BITS = HIGH_BIT - 1;
/// @dev The WETH token contract.
IEtherTokenV06 private immutable WETH;
constructor(
address zeroExAddress,
IEtherTokenV06 weth,
ILiquidityProviderSandbox sandbox,
address uniswapFactory,
address sushiswapFactory,
bytes32 uniswapPairInitCodeHash,
bytes32 sushiswapPairInitCodeHash
)
public
FixinEIP712(zeroExAddress)
MultiplexLiquidityProvider(sandbox)
MultiplexUniswapV2(
uniswapFactory,
sushiswapFactory,
uniswapPairInitCodeHash,
sushiswapPairInitCodeHash
)
{
WETH = weth;
}
/// @dev Initialize and register this feature.
/// Should be delegatecalled by `Migrate.migrate()`.
/// @return success `LibMigrate.SUCCESS` on success.
function migrate()
external
returns (bytes4 success)
{
_registerFeatureFunction(this.multiplexBatchSellEthForToken.selector);
_registerFeatureFunction(this.multiplexBatchSellTokenForEth.selector);
_registerFeatureFunction(this.multiplexBatchSellTokenForToken.selector);
_registerFeatureFunction(this.multiplexMultiHopSellEthForToken.selector);
_registerFeatureFunction(this.multiplexMultiHopSellTokenForEth.selector);
_registerFeatureFunction(this.multiplexMultiHopSellTokenForToken.selector);
return LibMigrate.MIGRATE_SUCCESS;
}
/// @dev Sells attached ETH for `outputToken` using the provided
/// calls.
/// @param outputToken The token to buy.
/// @param calls The calls to use to sell the attached ETH.
/// @param minBuyAmount The minimum amount of `outputToken` that
/// must be bought for this function to not revert.
/// @return boughtAmount The amount of `outputToken` bought.
function multiplexBatchSellEthForToken(
IERC20TokenV06 outputToken,
BatchSellSubcall[] memory calls,
uint256 minBuyAmount
)
public
override
payable
returns (uint256 boughtAmount)
{
// Wrap ETH.
WETH.deposit{value: msg.value}();
// WETH is now held by this contract,
// so `useSelfBalance` is true.
return _multiplexBatchSell(
BatchSellParams({
inputToken: WETH,
outputToken: outputToken,
sellAmount: msg.value,
calls: calls,
useSelfBalance: true,
recipient: msg.sender
}),
minBuyAmount
);
}
/// @dev Sells `sellAmount` of the given `inputToken` for ETH
/// using the provided calls.
/// @param inputToken The token to sell.
/// @param calls The calls to use to sell the input tokens.
/// @param sellAmount The amount of `inputToken` to sell.
/// @param minBuyAmount The minimum amount of ETH that
/// must be bought for this function to not revert.
/// @return boughtAmount The amount of ETH bought.
function multiplexBatchSellTokenForEth(
IERC20TokenV06 inputToken,
BatchSellSubcall[] memory calls,
uint256 sellAmount,
uint256 minBuyAmount
)
public
override
returns (uint256 boughtAmount)
{
// The outputToken is implicitly WETH. The `recipient`
// of the WETH is set to this contract, since we
// must unwrap the WETH and transfer the resulting ETH.
boughtAmount = _multiplexBatchSell(
BatchSellParams({
inputToken: inputToken,
outputToken: WETH,
sellAmount: sellAmount,
calls: calls,
useSelfBalance: false,
recipient: address(this)
}),
minBuyAmount
);
// Unwrap WETH.
WETH.withdraw(boughtAmount);
// Transfer ETH to `msg.sender`.
_transferEth(msg.sender, boughtAmount);
}
/// @dev Sells `sellAmount` of the given `inputToken` for
/// `outputToken` using the provided calls.
/// @param inputToken The token to sell.
/// @param outputToken The token to buy.
/// @param calls The calls to use to sell the input tokens.
/// @param sellAmount The amount of `inputToken` to sell.
/// @param minBuyAmount The minimum amount of `outputToken`
/// that must be bought for this function to not revert.
/// @return boughtAmount The amount of `outputToken` bought.
function multiplexBatchSellTokenForToken(
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
BatchSellSubcall[] memory calls,
uint256 sellAmount,
uint256 minBuyAmount
)
public
override
returns (uint256 boughtAmount)
{
return _multiplexBatchSell(
BatchSellParams({
inputToken: inputToken,
outputToken: outputToken,
sellAmount: sellAmount,
calls: calls,
useSelfBalance: false,
recipient: msg.sender
}),
minBuyAmount
);
}
/// @dev Executes a batch sell and checks that at least
/// `minBuyAmount` of `outputToken` was bought.
/// @param params Batch sell parameters.
/// @param minBuyAmount The minimum amount of `outputToken` that
/// must be bought for this function to not revert.
/// @return boughtAmount The amount of `outputToken` bought.
function _multiplexBatchSell(
BatchSellParams memory params,
uint256 minBuyAmount
)
private
returns (uint256 boughtAmount)
{
// Cache the recipient's initial balance of the output token.
uint256 balanceBefore = params.outputToken.balanceOf(params.recipient);
// Execute the batch sell.
BatchSellState memory state = _executeBatchSell(params);
// Compute the change in balance of the output token.
uint256 balanceDelta = params.outputToken.balanceOf(params.recipient)
.safeSub(balanceBefore);
// Use the minimum of the balanceDelta and the returned bought
// amount in case of weird tokens and whatnot.
boughtAmount = LibSafeMathV06.min256(balanceDelta, state.boughtAmount);
// Enforce `minBuyAmount`.
require(
boughtAmount >= minBuyAmount,
"MultiplexFeature::_multiplexBatchSell/UNDERBOUGHT"
);
}
/// @dev Sells attached ETH via the given sequence of tokens
/// and calls. `tokens[0]` must be WETH.
/// The last token in `tokens` is the output token that
/// will ultimately be sent to `msg.sender`
/// @param tokens The sequence of tokens to use for the sell,
/// i.e. `tokens[i]` will be sold for `tokens[i+1]` via
/// `calls[i]`.
/// @param calls The sequence of calls to use for the sell.
/// @param minBuyAmount The minimum amount of output tokens that
/// must be bought for this function to not revert.
/// @return boughtAmount The amount of output tokens bought.
function multiplexMultiHopSellEthForToken(
address[] memory tokens,
MultiHopSellSubcall[] memory calls,
uint256 minBuyAmount
)
public
override
payable
returns (uint256 boughtAmount)
{
// First token must be WETH.
require(
tokens[0] == address(WETH),
"MultiplexFeature::multiplexMultiHopSellEthForToken/NOT_WETH"
);
// Wrap ETH.
WETH.deposit{value: msg.value}();
// WETH is now held by this contract,
// so `useSelfBalance` is true.
return _multiplexMultiHopSell(
MultiHopSellParams({
tokens: tokens,
sellAmount: msg.value,
calls: calls,
useSelfBalance: true,
recipient: msg.sender
}),
minBuyAmount
);
}
/// @dev Sells `sellAmount` of the input token (`tokens[0]`)
/// for ETH via the given sequence of tokens and calls.
/// The last token in `tokens` must be WETH.
/// @param tokens The sequence of tokens to use for the sell,
/// i.e. `tokens[i]` will be sold for `tokens[i+1]` via
/// `calls[i]`.
/// @param calls The sequence of calls to use for the sell.
/// @param sellAmount The amount of `inputToken` to sell.
/// @param minBuyAmount The minimum amount of ETH that
/// must be bought for this function to not revert.
/// @return boughtAmount The amount of ETH bought.
function multiplexMultiHopSellTokenForEth(
address[] memory tokens,
MultiHopSellSubcall[] memory calls,
uint256 sellAmount,
uint256 minBuyAmount
)
public
override
returns (uint256 boughtAmount)
{
// Last token must be WETH.
require(
tokens[tokens.length - 1] == address(WETH),
"MultiplexFeature::multiplexMultiHopSellTokenForEth/NOT_WETH"
);
// The `recipient of the WETH is set to this contract, since
// we must unwrap the WETH and transfer the resulting ETH.
boughtAmount = _multiplexMultiHopSell(
MultiHopSellParams({
tokens: tokens,
sellAmount: sellAmount,
calls: calls,
useSelfBalance: false,
recipient: address(this)
}),
minBuyAmount
);
// Unwrap WETH.
WETH.withdraw(boughtAmount);
// Transfer ETH to `msg.sender`.
_transferEth(msg.sender, boughtAmount);
}
/// @dev Sells `sellAmount` of the input token (`tokens[0]`)
/// via the given sequence of tokens and calls.
/// The last token in `tokens` is the output token that
/// will ultimately be sent to `msg.sender`
/// @param tokens The sequence of tokens to use for the sell,
/// i.e. `tokens[i]` will be sold for `tokens[i+1]` via
/// `calls[i]`.
/// @param calls The sequence of calls to use for the sell.
/// @param sellAmount The amount of `inputToken` to sell.
/// @param minBuyAmount The minimum amount of output tokens that
/// must be bought for this function to not revert.
/// @return boughtAmount The amount of output tokens bought.
function multiplexMultiHopSellTokenForToken(
address[] memory tokens,
MultiHopSellSubcall[] memory calls,
uint256 sellAmount,
uint256 minBuyAmount
)
public
override
returns (uint256 boughtAmount)
{
return _multiplexMultiHopSell(
MultiHopSellParams({
tokens: tokens,
sellAmount: sellAmount,
calls: calls,
useSelfBalance: false,
recipient: msg.sender
}),
minBuyAmount
);
}
/// @dev Executes a multi-hop sell and checks that at least
/// `minBuyAmount` of output tokens were bought.
/// @param params Multi-hop sell parameters.
/// @param minBuyAmount The minimum amount of output tokens that
/// must be bought for this function to not revert.
/// @return boughtAmount The amount of output tokens bought.
function _multiplexMultiHopSell(
MultiHopSellParams memory params,
uint256 minBuyAmount
)
private
returns (uint256 boughtAmount)
{
// There should be one call/hop between every two tokens
// in the path.
// tokens[0]––calls[0]––>tokens[1]––...––calls[n-1]––>tokens[n]
require(
params.tokens.length == params.calls.length + 1,
"MultiplexFeature::_multiplexMultiHopSell/MISMATCHED_ARRAY_LENGTHS"
);
// The output token is the last token in the path.
IERC20TokenV06 outputToken = IERC20TokenV06(
params.tokens[params.tokens.length - 1]
);
// Cache the recipient's balance of the output token.
uint256 balanceBefore = outputToken.balanceOf(params.recipient);
// Execute the multi-hop sell.
MultiHopSellState memory state = _executeMultiHopSell(params);
// Compute the change in balance of the output token.
uint256 balanceDelta = outputToken.balanceOf(params.recipient)
.safeSub(balanceBefore);
// Use the minimum of the balanceDelta and the returned bought
// amount in case of weird tokens and whatnot.
boughtAmount = LibSafeMathV06.min256(balanceDelta, state.outputTokenAmount);
// Enforce `minBuyAmount`.
require(
boughtAmount >= minBuyAmount,
"MultiplexFeature::_multiplexMultiHopSell/UNDERBOUGHT"
);
}
/// @dev Iterates through the constituent calls of a batch
/// sell and executes each one, until the full amount
// has been sold.
/// @param params Batch sell parameters.
/// @return state A struct containing the amounts of `inputToken`
/// sold and `outputToken` bought.
function _executeBatchSell(BatchSellParams memory params)
private
returns (BatchSellState memory state)
{
// Iterate through the calls and execute each one
// until the full amount has been sold.
for (uint256 i = 0; i != params.calls.length; i++) {
// Check if we've hit our target.
if (state.soldAmount >= params.sellAmount) { break; }
BatchSellSubcall memory subcall = params.calls[i];
// Compute the input token amount.
uint256 inputTokenAmount = _normalizeSellAmount(
subcall.sellAmount,
params.sellAmount,
state.soldAmount
);
if (subcall.id == MultiplexSubcall.RFQ) {
_batchSellRfqOrder(
state,
params,
subcall.data,
inputTokenAmount
);
} else if (subcall.id == MultiplexSubcall.OTC) {
_batchSellOtcOrder(
state,
params,
subcall.data,
inputTokenAmount
);
} else if (subcall.id == MultiplexSubcall.UniswapV2) {
_batchSellUniswapV2(
state,
params,
subcall.data,
inputTokenAmount
);
} else if (subcall.id == MultiplexSubcall.UniswapV3) {
_batchSellUniswapV3(
state,
params,
subcall.data,
inputTokenAmount
);
} else if (subcall.id == MultiplexSubcall.LiquidityProvider) {
_batchSellLiquidityProvider(
state,
params,
subcall.data,
inputTokenAmount
);
} else if (subcall.id == MultiplexSubcall.TransformERC20) {
_batchSellTransformERC20(
state,
params,
subcall.data,
inputTokenAmount
);
} else if (subcall.id == MultiplexSubcall.MultiHopSell) {
_nestedMultiHopSell(
state,
params,
subcall.data,
inputTokenAmount
);
} else {
revert("MultiplexFeature::_executeBatchSell/INVALID_SUBCALL");
}
}
require(
state.soldAmount == params.sellAmount,
"MultiplexFeature::_executeBatchSell/INCORRECT_AMOUNT_SOLD"
);
}
// This function executes a sequence of fills "hopping" through the
// path of tokens given by `params.tokens`.
function _executeMultiHopSell(MultiHopSellParams memory params)
private
returns (MultiHopSellState memory state)
{
// This variable is used for the input and output amounts of
// each hop. After the final hop, this will contain the output
// amount of the multi-hop fill.
state.outputTokenAmount = params.sellAmount;
// The first call may expect the input tokens to be held by
// `msg.sender`, `address(this)`, or some other address.
// Compute the expected address and transfer the input tokens
// there if necessary.
state.from = _computeHopTarget(params, 0);
// If the input tokens are currently held by `msg.sender` but
// the first hop expects them elsewhere, perform a `transferFrom`.
if (!params.useSelfBalance && state.from != msg.sender) {
_transferERC20TokensFrom(
IERC20TokenV06(params.tokens[0]),
msg.sender,
state.from,
params.sellAmount
);
}
// If the input tokens are currently held by `address(this)` but
// the first hop expects them elsewhere, perform a `transfer`.
if (params.useSelfBalance && state.from != address(this)) {
_transferERC20Tokens(
IERC20TokenV06(params.tokens[0]),
state.from,
params.sellAmount
);
}
// Iterate through the calls and execute each one.
for (state.hopIndex = 0; state.hopIndex != params.calls.length; state.hopIndex++) {
MultiHopSellSubcall memory subcall = params.calls[state.hopIndex];
// Compute the recipient of the tokens that will be
// bought by the current hop.
state.to = _computeHopTarget(params, state.hopIndex + 1);
if (subcall.id == MultiplexSubcall.UniswapV2) {
_multiHopSellUniswapV2(
state,
params,
subcall.data
);
} else if (subcall.id == MultiplexSubcall.UniswapV3) {
_multiHopSellUniswapV3(state, subcall.data);
} else if (subcall.id == MultiplexSubcall.LiquidityProvider) {
_multiHopSellLiquidityProvider(
state,
params,
subcall.data
);
} else if (subcall.id == MultiplexSubcall.BatchSell) {
_nestedBatchSell(
state,
params,
subcall.data
);
} else {
revert("MultiplexFeature::_executeMultiHopSell/INVALID_SUBCALL");
}
// The recipient of the current hop will be the source
// of tokens for the next hop.
state.from = state.to;
}
}
function _nestedMultiHopSell(
IMultiplexFeature.BatchSellState memory state,
IMultiplexFeature.BatchSellParams memory params,
bytes memory data,
uint256 sellAmount
)
private
{
MultiHopSellParams memory multiHopParams;
// Decode the tokens and calls for the nested
// multi-hop sell.
(
multiHopParams.tokens,
multiHopParams.calls
) = abi.decode(
data,
(address[], MultiHopSellSubcall[])
);
multiHopParams.sellAmount = sellAmount;
// If the batch sell is using input tokens held by
// `address(this)`, then so should the nested
// multi-hop sell.
multiHopParams.useSelfBalance = params.useSelfBalance;
// Likewise, the recipient of the multi-hop sell is
// equal to the recipient of its containing batch sell.
multiHopParams.recipient = params.recipient;
// Execute the nested multi-hop sell.
uint256 outputTokenAmount =
_executeMultiHopSell(multiHopParams).outputTokenAmount;
// Increment the sold and bought amounts.
state.soldAmount = state.soldAmount.safeAdd(sellAmount);
state.boughtAmount = state.boughtAmount.safeAdd(outputTokenAmount);
}
function _nestedBatchSell(
IMultiplexFeature.MultiHopSellState memory state,
IMultiplexFeature.MultiHopSellParams memory params,
bytes memory data
)
private
{
BatchSellParams memory batchSellParams;
// Decode the calls for the nested batch sell.
batchSellParams.calls = abi.decode(
data,
(BatchSellSubcall[])
);
// The input and output tokens of the batch
// sell are the current and next tokens in
// `params.tokens`, respectively.
batchSellParams.inputToken = IERC20TokenV06(
params.tokens[state.hopIndex]
);
batchSellParams.outputToken = IERC20TokenV06(
params.tokens[state.hopIndex + 1]
);
// The `sellAmount` for the batch sell is the
// `outputTokenAmount` from the previous hop.
batchSellParams.sellAmount = state.outputTokenAmount;
// If the nested batch sell is the first hop
// and `useSelfBalance` for the containing multi-
// hop sell is false, the nested batch sell should
// pull tokens from `msg.sender` (so `batchSellParams.useSelfBalance`
// should be false). Otherwise `batchSellParams.useSelfBalance`
// should be true.
batchSellParams.useSelfBalance = state.hopIndex > 0 || params.useSelfBalance;
// `state.to` has been populated with the address
// that should receive the output tokens of the
// batch sell.
batchSellParams.recipient = state.to;
// Execute the nested batch sell.
state.outputTokenAmount =
_executeBatchSell(batchSellParams).boughtAmount;
}
// This function computes the "target" address of hop index `i` within
// a multi-hop sell.
// If `i == 0`, the target is the address which should hold the input
// tokens prior to executing `calls[0]`. Otherwise, it is the address
// that should receive `tokens[i]` upon executing `calls[i-1]`.
function _computeHopTarget(
MultiHopSellParams memory params,
uint256 i
)
private
view
returns (address target)
{
if (i == params.calls.length) {
// The last call should send the output tokens to the
// multi-hop sell recipient.
target = params.recipient;
} else {
MultiHopSellSubcall memory subcall = params.calls[i];
if (subcall.id == MultiplexSubcall.UniswapV2) {
// UniswapV2 (and Sushiswap) allow tokens to be
// transferred into the pair contract before `swap`
// is called, so we compute the pair contract's address.
(address[] memory tokens, bool isSushi) = abi.decode(
subcall.data,
(address[], bool)
);
target = _computeUniswapPairAddress(
tokens[0],
tokens[1],
isSushi
);
} else if (subcall.id == MultiplexSubcall.LiquidityProvider) {
// Similar to UniswapV2, LiquidityProvider contracts
// allow tokens to be transferred in before the swap
// is executed, so we the target is the address encoded
// in the subcall data.
(target,) = abi.decode(
subcall.data,
(address, bytes)
);
} else if (
subcall.id == MultiplexSubcall.UniswapV3 ||
subcall.id == MultiplexSubcall.BatchSell
) {
// UniswapV3 uses a callback to pull in the tokens being
// sold to it. The callback implemented in `UniswapV3Feature`
// can either:
// - call `transferFrom` to move tokens from `msg.sender` to the
// UniswapV3 pool, or
// - call `transfer` to move tokens from `address(this)` to the
// UniswapV3 pool.
// A nested batch sell is similar, in that it can either:
// - use tokens from `msg.sender`, or
// - use tokens held by `address(this)`.
// Suppose UniswapV3/BatchSell is the first call in the multi-hop
// path. The input tokens are either held by `msg.sender`,
// or in the case of `multiplexMultiHopSellEthForToken` WETH is
// held by `address(this)`. The target is set accordingly.
// If this is _not_ the first call in the multi-hop path, we
// are dealing with an "intermediate" token in the multi-hop path,
// which `msg.sender` may not have an allowance set for. Thus
// target must be set to `address(this)` for `i > 0`.
if (i == 0 && !params.useSelfBalance) {
target = msg.sender;
} else {
target = address(this);
}
} else {
revert("MultiplexFeature::_computeHopTarget/INVALID_SUBCALL");
}
}
require(
target != address(0),
"MultiplexFeature::_computeHopTarget/TARGET_IS_NULL"
);
}
// If `rawAmount` encodes a proportion of `totalSellAmount`, this function
// converts it to an absolute quantity. Caps the normalized amount to
// the remaining sell amount (`totalSellAmount - soldAmount`).
function _normalizeSellAmount(
uint256 rawAmount,
uint256 totalSellAmount,
uint256 soldAmount
)
private
pure
returns (uint256 normalized)
{
if ((rawAmount & HIGH_BIT) == HIGH_BIT) {
// If the high bit of `rawAmount` is set then the lower 255 bits
// specify a fraction of `totalSellAmount`.
return LibSafeMathV06.min256(
totalSellAmount
* LibSafeMathV06.min256(rawAmount & LOWER_255_BITS, 1e18)
/ 1e18,
totalSellAmount.safeSub(soldAmount)
);
} else {
return LibSafeMathV06.min256(
rawAmount,
totalSellAmount.safeSub(soldAmount)
);
}
}
}
|
Sells `sellAmount` of the given `inputToken` for ETH using the provided calls. inputToken The token to sell. calls The calls to use to sell the input tokens. sellAmount The amount of `inputToken` to sell. minBuyAmount The minimum amount of ETH that must be bought for this function to not revert. return boughtAmount The amount of ETH bought. The outputToken is implicitly WETH. The `recipient` of the WETH is set to this contract, since we must unwrap the WETH and transfer the resulting ETH.
|
function multiplexBatchSellTokenForEth(
IERC20TokenV06 inputToken,
BatchSellSubcall[] memory calls,
uint256 sellAmount,
uint256 minBuyAmount
)
public
override
returns (uint256 boughtAmount)
{
boughtAmount = _multiplexBatchSell(
BatchSellParams({
inputToken: inputToken,
outputToken: WETH,
sellAmount: sellAmount,
calls: calls,
useSelfBalance: false,
recipient: address(this)
}),
minBuyAmount
);
}
| 6,350,106 |
/**
*Submitted for verification at Etherscan.io on 2021-11-10
*/
// Sources flattened with hardhat v2.6.4 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts-upgradeable/utils/math/[email protected]
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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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;
}
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File contracts/extends/Salable.sol
pragma solidity ^0.8.0;
// ,--. ,--.,--. ,--. ,------.
// | | | || |,-' '-.,--.--. ,--,--.| .--. ' ,--,--.,--.--. ,---.
// | | | || |'-. .-'| .--'' ,-. || '--'.'' ,-. || .--'| .-. :
// ' '-' '| | | | | | \ '-' || |\ \ \ '-' || | \ --.
// `-----' `--' `--' `--' `--`--'`--' '--' `--`--'`--' `----'
//
//Common functionality for whitelisting, presales and sales
abstract contract Salable is ERC721Enumerable, Ownable {
uint256 public maxNFTCirculation;
bool public isWhitelistSaleActive;
bool public isPublicSaleActive;
bool public isPreSaleActive;
mapping(address => bool) public whitelist;
modifier onlyWhenPublicSaleIsActive {
require(isPublicSaleActive, "TCM: Public Sale Is Inactive");
_;
}
modifier onlyWhenWhitelistSaleIsActive {
require(isWhitelistSaleActive, "TCM: Whitelist Sale Is Inactive");
_;
}
modifier onlyWhenPreSaleIsActive {
require(isPreSaleActive, "TCM: Presale Is Inactive");
_;
}
//Toggle states
function setSaleActiveState(bool state) external onlyOwner {
if (state == true) {
require(isWhitelistSaleActive == false && isPreSaleActive == false, "Other sales not inactive");
}
isPublicSaleActive = state;
}
function setWhitelistSaleState(bool state) external onlyOwner {
if (state == true) {
require(isPublicSaleActive == false && isPreSaleActive == false, "Other sales not inactive");
}
isWhitelistSaleActive = state;
}
function setPreSaleState(bool state) external onlyOwner {
if (state == true) {
require(isPublicSaleActive == false && isWhitelistSaleActive == false, "Other sales not inactive");
}
isPreSaleActive = state;
}
//End Toggle states
//Allow us to whitelist in bulk
function addToWhitelistBulk(address[] memory addresses) external onlyOwner {
for(uint i = 0; i < addresses.length; i++) {
whitelist[addresses[i]] = true;
}
}
//Add an address to our whitelist
function addToWhitelist(address newAdd) external onlyOwner {
whitelist[newAdd] = true;
}
//Remove an address from our whitelist
function removeFromWhitelist(address remove) external onlyOwner {
whitelist[remove] = false;
}
//Allow the owner to mint a set of NFTs to airdrop
function mintForAirdrop(uint256 numberToMint) external onlyOwner {
require(totalSupply() + numberToMint <= maxNFTCirculation, "TCM: Cap exceeded");
for (uint256 i = 0; i < numberToMint; i++) {
_safeMint(msg.sender, totalSupply() + 1);
}
}
}
// File contracts/URMintPass.sol
pragma solidity ^0.8.0;
// ,--. ,--.,--. ,--. ,------.
// | | | || |,-' '-.,--.--. ,--,--.| .--. ' ,--,--.,--.--. ,---.
// | | | || |'-. .-'| .--'' ,-. || '--'.'' ,-. || .--'| .-. :
// ' '-' '| | | | | | \ '-' || |\ \ \ '-' || | \ --.
// `-----' `--' `--' `--' `--`--'`--' '--' `--`--'`--' `----'
//
// Ultra Rare Mint Pass - https://www.ultrarare.uk
contract URMintPass is ERC721, ERC721Enumerable, Ownable, Salable {
using SafeMathUpgradeable for uint256;
string public baseUri;
uint256 public mintCost;
address payable public urWallet;
mapping(address => bool) public hasBought;
constructor() ERC721("UltraRareMintPass", "URMP") {
isPublicSaleActive = false;
isWhitelistSaleActive = false;
//0.13 Ethereum
mintCost = 130000000000000000;
maxNFTCirculation = 666;
}
//Start overrides
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal virtual override(ERC721) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) {
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
//End overrides
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
//Set this, will eventually land on the IPFS once all is complete
function setBaseUri(string memory _baseUri) external onlyOwner {
baseUri = _baseUri;
}
//Withdraw to the UR defined wallet
function withdraw() external onlyOwner {
require(urWallet != address(0), "UR Empty");
urWallet.transfer(address(this).balance);
}
//Allows one mint pass per wallet to be minted in the public sale
function mintInPublic() external payable onlyWhenPublicSaleIsActive {
require(totalSupply() + 1 <= maxNFTCirculation, "TCM: Cap exceeded");
require(mintCost <= msg.value, "TCM: Incorrect Ether Value");
require(hasBought[msg.sender] == false, "TCM: User may only buy one pass");
hasBought[msg.sender] = true; //ensure user cannot purchase more than 1 mint pass
_safeMint(msg.sender, totalSupply() + 1);
}
//Allows an NFT to be whitelisted in the whitelist sale
function mintInWhitelist() external payable onlyWhenWhitelistSaleIsActive {
require(totalSupply() + 1 <= maxNFTCirculation, "TCM: Cap exceeded");
require(mintCost <= msg.value, "TCM: Incorrect Ether Value");
require(whitelist[msg.sender] == true, "User not in whitelist");
require(hasBought[msg.sender] == false, "TCM: User may only buy one pass");
hasBought[msg.sender] = true; //ensure user cannot purchase more than 1 mint pass
whitelist[msg.sender] = false; //remove from the whitelist so this person can't buy again
_safeMint(msg.sender, totalSupply() + 1);
}
//Sets our wallets to their initial values
function setWallets(address payable _urWallet) external onlyOwner {
urWallet = _urWallet;
}
}
// File contracts/TCM.sol
pragma solidity ^0.8.0;
// ,--. ,--.,--. ,--. ,------.
// | | | || |,-' '-.,--.--. ,--,--.| .--. ' ,--,--.,--.--. ,---.
// | | | || |'-. .-'| .--'' ,-. || '--'.'' ,-. || .--'| .-. :
// ' '-' '| | | | | | \ '-' || |\ \ \ '-' || | \ --.
// `-----' `--' `--' `--' `--`--'`--' '--' `--`--'`--' `----'
//
// Texas Chainsaw Massacre NFT - https://leatherfaces.io
contract TCM is ERC721, ERC721Enumerable, Ownable, Salable {
using SafeMathUpgradeable for uint256;
string public baseUri;
string public provenanceHash;
uint256 public mintCost;
uint256 public maxBuyAtOncePublic;
uint256 public maxBuyAtOncePresale;
address payable public urWallet;
address payable public tcmWallet;
address payable public jWallet;
mapping(uint256 => bool) public tokensUsedByMintPass;
address public mintPassAddress;
URMintPass private mintPass;
constructor(address newMintPassAddress) ERC721("TexasChainsawMassacre", "TCM") {
isPublicSaleActive = false;
isWhitelistSaleActive = false;
maxBuyAtOncePublic = 5;
maxBuyAtOncePresale = 3;
//0.0666 Ethereum
mintCost = 66600000000000000;
maxNFTCirculation = 1732;
mintPassAddress = newMintPassAddress;
mintPass = URMintPass(mintPassAddress);
}
//Start overrides
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal virtual override(ERC721) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
//End overrides
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
//Set this, will eventually land on the IPFS once all is complete
function setBaseUri(string memory _baseUri) external onlyOwner {
baseUri = _baseUri;
}
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
require(bytes(provenanceHash).length == 0, "PH already set");
provenanceHash = _provenanceHash;
}
//Sets our wallets to their initial values
function setWallets(
address payable _urWallet,
address payable _tcmWallet,
address payable _jWallet) external onlyOwner {
urWallet = _urWallet;
tcmWallet = _tcmWallet;
jWallet = _jWallet;
}
//Splits withdraw amongst 3 parties
function withdraw() external onlyOwner {
require(urWallet != address(0), "UR Empty");
require(tcmWallet != address(0), "TCM Empty");
require(jWallet != address(0), "J Empty");
uint256 amount45 = address(this).balance.mul(450).div(1000);
// 45%
uint256 amount10 = address(this).balance.mul(100).div(1000);
// 10%
urWallet.transfer(amount45);
tcmWallet.transfer(amount45);
jWallet.transfer(amount10);
}
//Allows NFTs to be minted in the main sale
function mintInPublic(uint256 numberToMint) external payable onlyWhenPublicSaleIsActive {
require(numberToMint <= maxBuyAtOncePublic, "TCM: Requested too many");
require(totalSupply() + numberToMint <= maxNFTCirculation, "TCM: Cap exceeded");
require(mintCost * numberToMint <= msg.value, "TCM: Incorrect Ether Value");
for (uint256 i = 0; i < numberToMint; i++) {
_safeMint(msg.sender, totalSupply() + 1);
}
}
//Allows an NFT to be bought in the whitelist sale
function mintInWhitelist() external payable onlyWhenWhitelistSaleIsActive {
require(totalSupply() + 1 <= maxNFTCirculation, "TCM: Cap exceeded");
require(mintCost <= msg.value, "TCM: Incorrect Ether Value");
require(whitelist[msg.sender] == true, "User not in whitelist");
whitelist[msg.sender] = false; //remove from the whitelist so this person can't buy again
_safeMint(msg.sender, totalSupply() + 1);
}
//Allows an NFT to be bought in the presale, by users with a mint pass
function mintInPresale(uint256 numberToBuy) external payable onlyWhenPreSaleIsActive {
uint256 numberToMint = numberToBuy + 1;
require(numberToBuy <= maxBuyAtOncePresale, "TCM: Requested too many");
require(totalSupply() + numberToMint <= maxNFTCirculation, "TCM: Cap exceeded");
require(mintCost * numberToBuy <= msg.value, "TCM: Incorrect Ether Value");
uint256 balanceOf = mintPass.balanceOf(msg.sender);
require(balanceOf > 0, "MP not owned");
bool minted = false;
//Loop through mint passes user owns, and find the first they have not used to purchase
for(uint256 bPos = 0; bPos < balanceOf; bPos++){
uint256 mintPassTokenIndex = mintPass.tokenOfOwnerByIndex(msg.sender, bPos);
if(tokensUsedByMintPass[mintPassTokenIndex] == false){
//Negate token, and mint
tokensUsedByMintPass[mintPassTokenIndex] = true;
for (uint256 i = 0; i < numberToMint; i++) {
_safeMint(msg.sender, totalSupply() + 1);
}
minted = true;
break; //used this mint pass, peace out!
}
}
require(minted == true, "MP already used");
}
}
|
Allow us to whitelist in bulk
|
function addToWhitelistBulk(address[] memory addresses) external onlyOwner {
for(uint i = 0; i < addresses.length; i++) {
whitelist[addresses[i]] = true;
}
}
| 6,688,603 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IStakingRewardsVault.sol";
import "../commons/MetaTransactionsMixin.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev {StakingManager}:
*/
contract StakingManager is Ownable, MetaTransactionsMixin {
using SafeERC20 for IERC20;
// Info for each user.
struct UserInfo {
uint256 amount; // LP token amount the user has provided.
int256 rewardDebt; // The amount of TSX entitled to the user.
}
// Info of each staking pool.
struct PoolInfo {
uint256 relativeWeight; // Weight of the staking pool.
uint256 accTSXPerShare; // Accumulated TSX per share, times 1e18. See below.
uint256 lastRewardTime; // Last block ts that TSX distribution occurs
}
// Address of Rewards Vault.
IStakingRewardsVault public rewardsVault;
// Info of each pool.
PoolInfo[] public poolInfo;
// Address of the LP token for each pool.
IERC20[] public lpToken;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Tokens added
mapping (address => bool) public addedTokens;
// Total weight. Must be the sum of all relative weight in all pools.
uint256 public totalWeight;
uint256 public claimablePerSecond;
uint256 private constant ACC_TSX_PRECISION = 1e18;
// Events
event Stake(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Unstake(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event EmergencyUnstake(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Claim(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event LogAddPool(
uint256 indexed pid,
uint256 relativeWeight,
address indexed lpToken
);
event LogSetPoolWeight(
uint256 indexed pid,
uint256 relativeWeight
);
event LogUpdatePool(
uint256 indexed pid,
uint256 lastRewardTime,
uint256 lpSupply,
uint256 accTSXPerShare
);
event LogClaimablePerSecond(uint256 claimablePerSecond);
/**
* @dev constructor
* @param _rewardsVault reward token address
*/
constructor(address _rewardsVault) Ownable() {
rewardsVault = IStakingRewardsVault(_rewardsVault);
}
/**
* @dev Returns the number of pools.
*/
function poolLength() public view returns (uint256) {
return poolInfo.length;
}
/**
* @dev Sets RewardVault
* @param _rewardsVault reward token address
*/
function setStakingRewardsVault(address _rewardsVault) external onlyOwner {
rewardsVault = IStakingRewardsVault(_rewardsVault);
}
/**
* @dev Adds a new LP. Can only be called by the owner.
* DO NOT add the same LP token more than once. Rewards will be messed up if you do.
* @param _relativeWeight amount of TSX to distribute per block.
* @param _lpToken Address of the LP ERC-20 token.
*/
function addPool(uint256 _relativeWeight, address _lpToken) external onlyOwner {
require(
addedTokens[_lpToken] == false,
"StakingManager(): Token already added"
);
totalWeight += _relativeWeight;
lpToken.push(IERC20(_lpToken));
poolInfo.push(
PoolInfo({
relativeWeight: _relativeWeight,
lastRewardTime: block.timestamp,
accTSXPerShare: 0
})
);
addedTokens[_lpToken] = true;
emit LogAddPool(
lpToken.length - 1,
_relativeWeight,
_lpToken
);
}
/**
* @dev Update the given pool's TSX allocation point.
* Can only be called by the owner.
* @param _pid The index of the pool. See `poolInfo`.
* @param _relativeWeight New AP of the pool.
*/
function setPoolWeight(uint256 _pid, uint256 _relativeWeight) external onlyOwner {
totalWeight -= poolInfo[_pid].relativeWeight;
totalWeight += _relativeWeight;
poolInfo[_pid].relativeWeight = _relativeWeight;
emit LogSetPoolWeight(
_pid,
_relativeWeight
);
}
/**
* @dev Sets the tsx per second to be distributed. Can only be called by the owner.
* @param _claimablePerSecond The amount of TSX to be distributed per second.
*/
function setClaimablePerSecond(uint256 _claimablePerSecond) external onlyOwner {
claimablePerSecond = _claimablePerSecond;
emit LogClaimablePerSecond(_claimablePerSecond);
}
/**
* @dev Update reward variables of the given pool.
* @param _pid The index of the pool. See `poolInfo`.
* @return pool Returns the pool that was updated.
*/
function updatePool(uint256 _pid) public returns (PoolInfo memory pool) {
pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return pool;
}
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp - pool.lastRewardTime;
uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight;
pool.accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply;
}
pool.lastRewardTime = block.timestamp;
poolInfo[_pid] = pool;
emit LogUpdatePool(
_pid,
pool.lastRewardTime,
lpSupply,
pool.accTSXPerShare
);
}
/**
* @dev Update reward variables for all pools. Be careful of gas spending!
* @param _pids Pool IDs of all to be updated. Make sure to update all active pools.
*/
function massUpdatePools(uint256[] calldata _pids) external {
uint256 len = _pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(_pids[i]);
}
}
/**
* @dev Stake LP tokens for TSX allocation.
* @param _pid The index of the pool. See `poolInfo`.
* @param _amount LP token amount to deposit.
*/
function stake(uint256 _pid, uint256 _amount) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
// Effects
user.amount += _amount;
user.rewardDebt += int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
// Transfer LP tokens
lpToken[_pid].safeTransferFrom(
senderAddr,
address(this),
_amount
);
emit Stake(senderAddr, _pid, _amount);
}
/**
* @dev Unstake LP tokens.
* @param _pid The index of the pool. See `poolInfo`.
* @param _amount LP token amount to unstake.
*/
function unstake(uint256 _pid, uint256 _amount) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
// Effects
user.rewardDebt -= int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
user.amount -= _amount;
// Unstake LP tokens
lpToken[_pid].safeTransfer(senderAddr, _amount);
emit Unstake(senderAddr, _pid, _amount);
}
/**
* @dev Claim proceeds for transaction sender to `to`.
* @param _pid The index of the pool. See `poolInfo`.
*/
function claim(uint256 _pid) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
int256 accumulatedTSX = int256(user.amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
uint256 pendingTSX = uint256(accumulatedTSX - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedTSX;
// Rewards
rewardsVault.sendRewards(senderAddr, pendingTSX);
emit Claim(senderAddr, _pid, pendingTSX);
}
/**
* @dev Unstake LP tokens and claim proceeds for transaction sender to `to`.
* @param _pid The index of the pool. See `poolInfo`.
* @param _amount LP token amount to unstake.
*/
function unstakeAndClaim(uint256 _pid, uint256 _amount) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
int256 accumulatedTSX = int256(user.amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
uint256 pendingTSX = uint256(accumulatedTSX - user.rewardDebt);
// Effects
user.rewardDebt = accumulatedTSX - int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
user.amount -= _amount;
// Reward
rewardsVault.sendRewards(senderAddr, pendingTSX);
// Unstake LP tokens
lpToken[_pid].safeTransfer(senderAddr, _amount);
emit Unstake(senderAddr, _pid, _amount);
emit Claim(senderAddr, _pid, pendingTSX);
}
/**
* @dev Unstake without caring about rewards. EMERGENCY ONLY.
* @param _pid The index of the pool. See `poolInfo`.
*/
function emergencyUnstake(uint256 _pid) public {
address senderAddr = msgSender();
UserInfo storage user = userInfo[_pid][senderAddr];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
// Unstake LP tokens
lpToken[_pid].safeTransfer(senderAddr, amount);
emit EmergencyUnstake(senderAddr, _pid, amount);
}
/**
* @dev View function to see pending TSX on frontend.
* @param _pid The index of the pool. See `poolInfo`.
* @param _user Address of user.
* @return pending TSX reward for a given user.
*/
function pendingRewards(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTSXPerShare = pool.accTSXPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint256 time = block.timestamp - pool.lastRewardTime;
uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight;
accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply;
}
return uint256(
int256(user.amount * accTSXPerShare / ACC_TSX_PRECISION) - user.rewardDebt
);
}
}
|
Claim proceeds for transaction sender to `to`. _pid The index of the pool. See `poolInfo`./ Effects Rewards
|
function claim(uint256 _pid) public {
address senderAddr = msgSender();
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][senderAddr];
int256 accumulatedTSX = int256(user.amount * pool.accTSXPerShare / ACC_TSX_PRECISION);
uint256 pendingTSX = uint256(accumulatedTSX - user.rewardDebt);
user.rewardDebt = accumulatedTSX;
rewardsVault.sendRewards(senderAddr, pendingTSX);
emit Claim(senderAddr, _pid, pendingTSX);
}
| 13,138,820 |
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT
// An instance can be found on mainnet here: 0xc4D6D61da34446Dc9Adc540Db748d3b9CAEaf140
/**
Copyright (c) 2020 Austin Williams
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.
**/
interface IESDS {
function transferCoupons(address _sender, address _recipient, uint256 _epoch, uint256 _amount) external;
function balanceOfCoupons(address _account, uint256 _epoch) external view returns (uint256);
function allowanceCoupons(address _owner, address _spender) external view returns (uint256);
}
interface IERC20 {
function transferFrom(address _sender, address _recipient, uint256 _amount) external returns (bool);
function balanceOf(address _account) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
}
contract CouponTrader {
using SafeMath for uint256;
IESDS constant private ESDS = IESDS(0x443D2f2755DB5942601fa062Cc248aAA153313D3);
IERC20 constant private USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
uint256 constant private HOUSE_RATE = 100; // 100 basis points (1%) -- fee taken by the house
address constant private OPEN_SALE_INDICATOR = 0x0000000000000000000000000000000000000001; // if this is the "buyer" then anyone can buy
address public house = 0xE1dba80BAc43407360c7b0175444893eBaA30098; // collector of house take
struct Offer {
address buyer; // use OPEN_SALE_INDICATOR as the buyer address if you want to allow anyone to take the offer
uint256 epoch;
uint256 numCoupons; // 18 decimals
uint256 totalUSDCRequiredFromSeller; // 6 decimals
}
mapping (address => Offer) private offerBySeller;
event OfferSet(address indexed seller, address indexed buyer, uint256 indexed epoch, uint256 numCoupons, uint256 totalUSDCRequiredFromSeller);
event SuccessfulTrade(address indexed seller, address indexed buyer, uint256 epoch, uint256 numCoupons, uint256 totalUSDCRequiredFromSeller);
/** ========================
STATE MUTATING FUNCTIONS
======================== **/
// @notice Allows a seller to set or update an offer
// @notice Caller MUST have approved this contract to move their coupons before calling this function or else this will revert.
// @dev Does some sanity checks to make sure the seller can hold up their end. This check
// is for UX purposes only and can be bypassed trivially. It is not security critical.
// @param _buyer The buyer who is allowed to take this offer. If the _buyer param is set to OPEN_SALE_INDICATOR then
// anyone can take this offer.
// @param _epoch The epoch of the coupons to be sold.
// @param _numCoupons The number of coupons to be sold.
// @param _totalUSDCRequiredFromSeller The amount of USDC the buyer must pay to take this offer. Remember that USDC uses 6 decimal places, not 18.
function setOffer(address _buyer, uint256 _epoch, uint256 _numCoupons, uint256 _totalUSDCRequiredFromSeller) external {
// sanity checks
require(ESDS.balanceOfCoupons(msg.sender, _epoch) >= _numCoupons, "seller doesn't have enough coupons at that epoch");
require(ESDS.allowanceCoupons(msg.sender, address(this)) >= _numCoupons, "seller hasn't approved this contract to move enough coupons");
require(_totalUSDCRequiredFromSeller > 0, "_totalUSDCRequiredFromSeller is zero -- use the revokeOffer function");
// store new offer
Offer memory newOffer = Offer(_buyer, _epoch, _numCoupons, _totalUSDCRequiredFromSeller);
offerBySeller[msg.sender] = newOffer;
emit OfferSet(msg.sender, _buyer, _epoch, _numCoupons, _totalUSDCRequiredFromSeller);
}
// @notice A convenience function a seller can use to revoke their offer.
function revokeOffer() external {
delete offerBySeller[msg.sender];
emit OfferSet(msg.sender, address(0), 0, 0, 0);
}
// @notice Allows a buyer to take an offer.
// @dev Partial fills are not supported.
// @dev The buyer must have approved this contract to move enough USDC to pay for this purchase.
// @param _seller The seller whose offer the caller wants to take.
// @param _epoch The epoch of the coupons being bought (must match the seller's offer).
// @param _numCoupons The number of coupons being bought (must match the seller's offer).
// @param _totalUSDCRequiredFromSeller The amount of USDC the buyer is paying (must match the seller's offer).
function takeOffer(address _seller, uint256 _epoch, uint256 _numCoupons, uint256 _totalUSDCRequiredFromSeller) external {
// get offer information
Offer memory offer = offerBySeller[_seller];
// check that the caller is authorized
require(msg.sender == offer.buyer || offer.buyer == OPEN_SALE_INDICATOR, "unauthorized buyer");
// check that the order details are correct (protects buyer from frontrunning by the seller)
require(
offer.epoch == _epoch &&
offer.numCoupons == _numCoupons &&
offer.totalUSDCRequiredFromSeller == _totalUSDCRequiredFromSeller,
"order details do not match the seller's offer"
);
// delete the seller's offer (so this offer cannot be filled twice)
delete offerBySeller[_seller];
// compute house take and seller take (USDC)
uint256 houseTake = offer.totalUSDCRequiredFromSeller.mul(HOUSE_RATE).div(10_000);
uint256 sellerTake = offer.totalUSDCRequiredFromSeller.sub(houseTake);
// pay the seller USDC
require(USDC.transferFrom(msg.sender, _seller, sellerTake), "could not pay seller");
// pay the house USDC
require(USDC.transferFrom(msg.sender, house, houseTake), "could not pay house");
// transfer the coupons to the buyer
ESDS.transferCoupons(_seller, msg.sender, _epoch, _numCoupons); // @audit-ok reverts on failure
// emit events
emit SuccessfulTrade(_seller, msg.sender, _epoch, _numCoupons, _totalUSDCRequiredFromSeller);
emit OfferSet(_seller, address(0), 0, 0, 0);
}
// @notice Allows house address to change the house address
function changeHouseAddress(address _newAddress) external {
require(msg.sender == house);
house = _newAddress;
}
/** ======================
NON-MUTATING FUNCTIONS
====================== **/
// @notice A getter for the offers
// @param _seller The address of the seller whose offer we want to return.
function getOffer(address _seller) external view returns (address, uint256, uint256, uint256) {
Offer memory offer = offerBySeller[_seller];
return (offer.buyer, offer.epoch, offer.numCoupons, offer.totalUSDCRequiredFromSeller);
}
// @notice Returns true iff the _buyer is authorized to take the _offer offer.
function isAuthorizedBuyer(Offer memory _offer, address _buyer) public pure returns (bool) {
return ( _buyer == _offer.buyer || _offer.buyer == OPEN_SALE_INDICATOR );
}
// @notice Returns true iff all the details passed match the _offer.
function detailsMatch(Offer memory _offer, uint256 _epoch, uint256 _numCoupons, uint256 _totalUSDCRequiredFromSeller) public pure returns (bool) {
return (
_offer.epoch == _epoch &&
_offer.numCoupons == _numCoupons &&
_offer.totalUSDCRequiredFromSeller == _totalUSDCRequiredFromSeller
);
}
// @notice Returns true iff the _seller holds at least _numCoupons coupons.
function sellerHasTheCoupons(address _seller, uint256 _epoch, uint256 _numCoupons) public view returns (bool) {
return ( ESDS.balanceOfCoupons(_seller, _epoch) >= _numCoupons );
}
// @notice Returns true iff the _seller has approve this contract to move at least _numCoupons coupons.
function sellerHasApprovedCoupons(address _seller, uint256 _numCoupons) public view returns (bool) {
return ( ESDS.allowanceCoupons(_seller, address(this)) >= _numCoupons );
}
// @notice Returns true iff the _buyer holds at least _totalUSDCRequiredFromSeller USDC.
function buyerHasTheUSDC(address _buyer, uint256 _totalUSDCRequiredFromSeller) public view returns (bool) {
return ( USDC.balanceOf(_buyer) >= _totalUSDCRequiredFromSeller );
}
// @notice Returns true iff the _buyer has approve this contract to move at least _totalUSDCRequiredFromSeller USDC.
function buyerHasApprovedUSDC(address _buyer, uint256 _totalUSDCRequiredFromSeller) public view returns (bool) {
return ( USDC.allowance(_buyer, address(this)) >= _totalUSDCRequiredFromSeller );
}
// @notice Returns true iff the entered offer would likely succeed if taken by the _buyer right now.
// @dev This is just for UI convenience. It should not be relied upon for anything security-related.
function tradeShouldSucceed(address _buyer, address _seller, uint256 _epoch, uint256 _numCoupons, uint256 _totalUSDCRequiredFromSeller)
external
view
returns (bool)
{
Offer memory offer = offerBySeller[_seller];
return (
isAuthorizedBuyer(offer, _buyer) &&
detailsMatch(offer, _epoch, _numCoupons, _totalUSDCRequiredFromSeller) &&
sellerHasTheCoupons(_seller, _epoch, _numCoupons) &&
sellerHasApprovedCoupons(_seller, _numCoupons) &&
buyerHasTheUSDC(_buyer, _totalUSDCRequiredFromSeller) &&
buyerHasApprovedUSDC(_buyer, _totalUSDCRequiredFromSeller)
);
}
// @notice Convenience function for encoding offers.
function offerEncoder(address _buyer, uint256 _epoch, uint256 _numCoupons, uint256 _totalUSDCRequiredFromSeller)
external
pure
returns (Offer memory)
{
return Offer(_buyer, _epoch, _numCoupons, _totalUSDCRequiredFromSeller);
}
}
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;
}
}
|
Returns true iff the _buyer has approve this contract to move at least _totalUSDCRequiredFromSeller USDC.
|
function buyerHasApprovedUSDC(address _buyer, uint256 _totalUSDCRequiredFromSeller) public view returns (bool) {
return ( USDC.allowance(_buyer, address(this)) >= _totalUSDCRequiredFromSeller );
}
| 12,794,242 |
pragma solidity ^0.4.24;
// File: contracts/ERC20-token.sol
/**
* @title ERC20 interface
*
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts/OwnableWithAdmin.sol
/**
* @title OwnableWithAdmin
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract OwnableWithAdmin {
address public owner;
address public adminOwner;
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;
adminOwner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(msg.sender == adminOwner);
_;
}
/**
* @dev Throws if called by any account other than the owner or admin.
*/
modifier onlyOwnerOrAdmin() {
require(msg.sender == adminOwner || 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 adminOwner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferAdminOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(adminOwner, newOwner);
adminOwner = newOwner;
}
}
// File: contracts/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// 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 numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
// File: contracts/AirDropLight.sol
/**
* @title AirDrop Light Direct Airdrop
* @notice Contract is not payable.
* Owner or admin can allocate tokens.
* Tokens will be released direct.
*
*
*/
contract AirDropLight is OwnableWithAdmin {
using SafeMath for uint256;
// Amount of tokens claimed
uint256 public grandTotalClaimed = 0;
// The token being sold
ERC20 public token;
// Max amount in one airdrop
uint256 maxDirect = 51 * (10**uint256(18));
// Recipients
mapping(address => bool) public recipients;
// List of all addresses
address[] public addresses;
constructor(ERC20 _token) public {
require(_token != address(0));
token = _token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () public {
//Not payable
}
/**
* @dev Transfer tokens direct
* @param _recipients Array of wallets
* @param _tokenAmount Amount Allocated tokens + 18 decimals
*/
function transferManyDirect (address[] _recipients, uint256 _tokenAmount) onlyOwnerOrAdmin public{
for (uint256 i = 0; i < _recipients.length; i++) {
transferDirect(_recipients[i],_tokenAmount);
}
}
/**
* @dev Transfer tokens direct to recipient without allocation.
* _recipient can only get one transaction and _tokens can't be above maxDirect value
*
*/
function transferDirect(address _recipient,uint256 _tokens) public{
//Check if contract has tokens
require(token.balanceOf(this)>=_tokens);
//Check max value
require(_tokens < maxDirect );
//Check if _recipient already have got tokens
require(!recipients[_recipient]);
recipients[_recipient] = true;
//Transfer tokens
require(token.transfer(_recipient, _tokens));
//Add claimed tokens to grandTotalClaimed
grandTotalClaimed = grandTotalClaimed.add(_tokens);
}
// Allow transfer of tokens back to owner or reserve wallet
function returnTokens() public onlyOwner {
uint256 balance = token.balanceOf(this);
require(token.transfer(owner, balance));
}
// Owner can transfer tokens that are sent here by mistake
function refundTokens(address _recipient, ERC20 _token) public onlyOwner {
uint256 balance = _token.balanceOf(this);
require(_token.transfer(_recipient, balance));
}
}
// File: contracts/ZBX/ZBXAirDropLight.sol
/**
* @title BYTMAirDropLight
*
*
*/
contract ZBXAirDropLight is AirDropLight {
constructor(
ERC20 _token
) public AirDropLight(_token) {
}
}
|
Owner can transfer tokens that are sent here by mistake
|
function refundTokens(address _recipient, ERC20 _token) public onlyOwner {
uint256 balance = _token.balanceOf(this);
require(_token.transfer(_recipient, balance));
}
| 12,762,720 |
/**
*Submitted for verification at Etherscan.io on 2019-03-11
*/
pragma solidity ^0.5.1;
contract tokenRecipientInterface {
function receiveApproval(address _from, uint256 _value, address _token, bytes memory _extraData) public;
}
contract ERC20TokenInterface {
function totalSupply() public view returns (uint256 _totalSupply);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract SafeMath {
uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) {
require(x <= MAX_UINT256 - y);
return x + y;
}
function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) {
require(x >= y);
return x - y;
}
function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (y == 0) {
return 0;
}
require(x <= (MAX_UINT256 / y));
return x * y;
}
}
contract Owned {
address payable public owner;
address payable public newOwner;
constructor() public{
//owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0x0);
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
contract Lockable is Owned {
uint256 public lockedUntilBlock;
event ContractLocked(uint256 _untilBlock, string _reason);
modifier lockAffected {
require(block.number > lockedUntilBlock);
_;
}
function lockFromSelf(uint256 _untilBlock, string memory _reason) internal {
lockedUntilBlock = _untilBlock;
emit ContractLocked(_untilBlock, _reason);
}
function lockUntil(uint256 _untilBlock, string memory _reason) onlyOwner public {
lockedUntilBlock = _untilBlock;
emit ContractLocked(_untilBlock, _reason);
}
}
contract ERC20Token is ERC20TokenInterface, SafeMath, Owned, Lockable {
// Name of token
string public name;
// Abbreviation of tokens name
string public symbol;
// Number of decimals token has
uint8 public decimals;
// Maximum tokens that can be minted
uint256 public totalSupplyLimit;
// Current supply of tokens
uint256 supply = 0;
// Map of users balances
mapping (address => uint256) balances;
// Map of users allowances
mapping (address => mapping (address => uint256)) allowances;
// Event that shows that new tokens were created
event Mint(address indexed _to, uint256 _value);
// Event that shows that old tokens were destroyed
event Burn(address indexed _from, uint _value);
/**
* @dev Returns number of tokens in circulation
*
* @return total number od tokens
*/
function totalSupply() public view returns (uint256) {
return supply;
}
/**
* @dev Returns the balance of specific account
*
* @param _owner The account that caller wants to querry
* @return the balance on this account
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev User can transfer tokens with this method, method is disabled if emergencyLock is activated
*
* @param _to Reciever of tokens
* @param _value The amount of tokens that will be sent
* @return if successful returns true
*/
function transfer(address _to, uint256 _value) lockAffected public returns (bool success) {
require(_to != address(0x0) && _to != address(this));
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev This is used to allow some account to utilise transferFrom and sends tokens on your behalf, this method is disabled if emergencyLock is activated
*
* @param _spender Who can send tokens on your behalf
* @param _value The amount of tokens that are allowed to be sent
* @return if successful returns true
*/
function approve(address _spender, uint256 _value) lockAffected public returns (bool success) {
allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev This is used to send tokens and execute code on other smart contract, this method is disabled if emergencyLock is activated
*
* @param _spender Contract that is receiving tokens
* @param _value The amount that msg.sender is sending
* @param _extraData Additional params that can be used on reciving smart contract
* @return if successful returns true
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) lockAffected public returns (bool success) {
tokenRecipientInterface spender = tokenRecipientInterface(_spender);
approve(_spender, _value);
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
/**
* @dev Sender can transfer tokens on others behalf, this method is disabled if emergencyLock is activated
*
* @param _from The account that will send tokens
* @param _to Account that will recive the tokens
* @param _value The amount that msg.sender is sending
* @return if successful returns true
*/
function transferFrom(address _from, address _to, uint256 _value) lockAffected public returns (bool success) {
require(_to != address(0x0) && _to != address(this));
balances[_from] = safeSub(balanceOf(_from), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
allowances[_from][msg.sender] = safeSub(allowances[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Owner can transfer tokens on others behalf withouth any allowance
*
* @param _from The account that will send tokens
* @param _to Account that will recive the tokens
* @param _value The amount that msg.sender is sending
* @return if successful returns true
*/
function ownerTransferFrom(address _from, address _to, uint256 _value) onlyOwner public returns (bool success) {
balances[_from] = safeSub(balanceOf(_from), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Returns the amount od tokens that can be sent from this addres by spender
*
* @param _owner Account that has tokens
* @param _spender Account that can spend tokens
* @return remaining balance to spend
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowances[_owner][_spender];
}
/**
* @dev Creates new tokens as long as total supply does not reach limit
*
* @param _to Reciver od newly created tokens
* @param _amount Amount of tokens to be created;
*/
function mintTokens(address _to, uint256 _amount) onlyOwner public {
require(supply + _amount <= totalSupplyLimit);
supply = safeAdd(supply, _amount);
balances[_to] = safeAdd(balances[_to], _amount);
emit Mint(_to, _amount);
emit Transfer(address(0x0), _to, _amount);
}
/**
* @dev Destroys the amount of tokens and lowers total supply
*
* @param _amount Number of tokens user wants to destroy
*/
function burn(uint _amount) public {
balances[msg.sender] = safeSub(balanceOf(msg.sender), _amount);
supply = safeSub(supply, _amount);
emit Burn(msg.sender, _amount);
emit Transfer(msg.sender, address(0x0), _amount);
}
/**
* @dev Saves exidentaly sent tokens to this contract, can be used only by owner
*
* @param _tokenAddress Address of tokens smart contract
* @param _to Where to send the tokens
* @param _amount The amount of tokens that we are salvaging
*/
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public {
ERC20TokenInterface(_tokenAddress).transfer(_to, _amount);
}
/**
* @dev Disables the contract and wipes all the balances, can be used only by owner
*/
function killContract() public onlyOwner {
selfdestruct(owner);
}
}
contract MRPROTokenContract is ERC20Token {
/**
* @dev Intialises token and all the necesary variable
*/
constructor() public {
owner = 0xa12F88dC40BA5629C87D37d20EE46759b6a2f6ac;
name = "Test MRPRO";
symbol = "TestMRPRO";
decimals = 18;
totalSupplyLimit = 1000000000 * 10**18;
}
}
|
Owner can transfer tokens on others behalf withouth any allowance _from The account that will send tokens _to Account that will recive the tokens _value The amount that msg.sender is sending return if successful returns true/
|
function ownerTransferFrom(address _from, address _to, uint256 _value) onlyOwner public returns (bool success) {
balances[_from] = safeSub(balanceOf(_from), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
emit Transfer(_from, _to, _value);
return true;
}
| 6,882,368 |
/**
*Submitted for verification at Etherscan.io on 2022-04-19
*/
/**
*Submitted for verification at Etherscan.io on 2021-08-28
*/
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.10;
/**
* @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);
}
/**
* @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;
}
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
}
}
}
/*
* @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;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @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;
string internal _tokenURI;
// 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;
}
/// @notice It all points to base reality being a higher order of consciousness, take a deep dive into the work of Jacobo Grinberg.
function _baseURI() internal view returns (string memory) {
return _tokenURI;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory uri = _baseURI();
return uri;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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);
}
/**
* @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();
}
}
contract BlockBorgsAccessCard is ERC721Enumerable, Ownable {
constructor() ERC721('BlockBorgs Access Card','BAC'){
_tokenURI = 'https://ipfs.io/ipfs/QmSiRMUcUNvFDeyRGqyUNmsRxHARGHzZDuQXzoYay9izTt';
}
function mintToken(uint256 _count,address _recipient) public onlyOwner {
for(uint256 i=0; i<_count; i++){
_mint(_recipient,totalSupply());
}
}
}
|
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
|
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
pragma solidity 0.8.10;
}
| 10,550,538 |
//Address: 0xdbabbcb1e314facb908c3e06b1f483124a627ce0
//Contract name: STANToken
//Balance: 0 Ether
//Verification Date: 8/25/2017
//Transacion Count: 1
// CODE STARTS HERE
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity ^0.4.10;
contract Token {
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract IMigrationContract {
function migrate(address addr, uint256 uip) returns (bool success);
}
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;
}
}
/* ERC 20 token */
contract StandardToken is Token {
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;
}
contract STANToken is StandardToken, SafeMath {
// metadata
string public constant name = "STANToken";
string public constant symbol = "STAN";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // deposit address for ETH for UnlimitedIP Team.
address public newContractAddr; // the new contract for UnlimitedIP token updates;
// crowdsale parameters
bool public isFunding; // switched to true in operational state
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // current supply tokens for sell
uint256 public tokenRaised = 0; // the number of total sold token
uint256 public tokenMigrated = 0; // the number of total transferted token
uint256 public tokenExchangeRate = 1000; // 1000 UIP tokens per 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // allocate token for private sale;
event IssueToken(address indexed _to, uint256 _value); // issue token for public sale;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
event Burn(address indexed from, uint256 _value);
// format decimals.
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function STANToken()
{
ethFundDeposit = 0xa1e57e38f347f4CCCb441366A35d949142fAd7b0;
isFunding = false; //controls pre through crowdsale state
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(0);
totalSupply = formatDecimals(100000000);
require(currentSupply <= totalSupply);
balances[ethFundDeposit] = totalSupply-currentSupply;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// @dev set the token's tokenExchangeRate,
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
require(_tokenExchangeRate > 0);
require(_tokenExchangeRate != tokenExchangeRate);
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev increase the token's supply
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
require (value + currentSupply <= totalSupply);
require (balances[msg.sender] >= value && value>0);
balances[msg.sender] -= value;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev decrease the token's supply
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
require (value + tokenRaised < currentSupply);
require (value <= currentSupply - tokenRaised);
currentSupply = safeSubtract(currentSupply, value);
balances[msg.sender] += value;
DecreaseSupply(value);
}
/// @dev turn on the funding state
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
require(!isFunding);
require(_fundingStartBlock < _fundingStopBlock);
require(block.number < _fundingStartBlock) ;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// @dev turn off the funding state
function stopFunding() isOwner external {
require(isFunding);
isFunding = false;
}
/// @dev set a new contract for recieve the tokens (for update contract)
function setMigrateContract(address _newContractAddr) isOwner external {
require(_newContractAddr != newContractAddr);
newContractAddr = _newContractAddr;
}
/// @dev set a new owner.
function changeOwner(address _newFundDeposit) isOwner() external {
require(_newFundDeposit != address(0x0));
ethFundDeposit = _newFundDeposit;
}
/// sends the tokens to new contract
function migrate() external {
require(!isFunding);
require(newContractAddr != address(0x0));
uint256 tokens = balances[msg.sender];
require (tokens > 0);
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
require(newContract.migrate(msg.sender, tokens));
Migrate(msg.sender, tokens); // log it
}
/// @dev withdraw ETH from contract to UnlimitedIP team address
function transferETH() isOwner external {
require(this.balance > 0);
require(ethFundDeposit.send(this.balance));
}
/// @dev allocates UIP tokens to pre-sell address.
function allocateToken (address _addr, uint256 _eth) isOwner external {
require(_eth != 0);
require(_addr != address(0x0));
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
require(tokens + tokenRaised <= currentSupply);
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // logs token issued
}
function burn(uint256 _value) isOwner returns (bool success){
uint256 value = formatDecimals(_value);
require(balances[msg.sender] >= value);
balances[msg.sender] -= value;
totalSupply -= value;
Burn(msg.sender,value);
return true;
}
/// buys the tokens
function () payable {
require (isFunding);
require(msg.value > 0);
require(block.number >= fundingStartBlock);
require(block.number <= fundingStopBlock);
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
require(tokens + tokenRaised <= currentSupply);
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); // logs token issued
}
}
|
decrease the token's supply
|
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
require (value + tokenRaised < currentSupply);
require (value <= currentSupply - tokenRaised);
currentSupply = safeSubtract(currentSupply, value);
balances[msg.sender] += value;
DecreaseSupply(value);
}
| 15,882,722 |
./full_match/80001/0xa06587A30877C44e16B7A83e03AB408aFadFE821/sources/contracts/Bridge.sol
|
Verifies that chain signature is valid typeHash abi encoded type hash digest nonce Prevent replay attacks v Last byte of the signed PERMIT_DIGEST r First 32 bytes of the signed PERMIT_DIGEST v 32-64 bytes of the signed PERMIT_DIGEST Recover the signer of the PERMIT_DIGEST Compare the recover and the required signer
|
function signatureVerification(
bytes32 typeHash,
uint256 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(!nonces[nonce], "Bridge: request already processed!");
bytes32 permitDigest = EIP712Utils.getPermitDigest(typeHash);
address signer = ecrecover(permitDigest, v, r, s);
require(signer == botMessenger, "Bridge: invalid signature!");
nonces[nonce] = true;
lastNonce = nonce;
}
| 869,073 |
pragma solidity ^0.5.0;
contract OZStorage {
mapping (address => uint256) public _balances;
mapping (address => mapping (address => uint256)) public _allowed;
uint256 public _totalSupply;
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function totalSupply() internal view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _investor) internal view returns(uint256) {
return _balances[_investor];
}
}
|
counter to allow mutex lock with only one SSTORE operation
|
function totalSupply() internal view returns (uint256) {
return _totalSupply;
}
| 909,404 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {AddressAliasHelper} from '../../standards/AddressAliasHelper.sol';
import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol';
import {Lib_AddressResolver} from '../../libraries/resolver/Lib_AddressResolver.sol';
/* Interface Imports */
import {ICanonicalTransactionChain} from './ICanonicalTransactionChain.sol';
import {IChainStorageContainer} from './IChainStorageContainer.sol';
/**
* @title CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
*
* Runtime target: EVM
*/
contract CanonicalTransactionChain is
ICanonicalTransactionChain,
Lib_AddressResolver
{
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 public constant MIN_ROLLUP_TX_GAS = 100000;
uint256 public constant MAX_ROLLUP_TX_SIZE = 50000;
// The approximate cost of calling the enqueue function
uint256 public enqueueGasCost;
// The ratio of the cost of L1 gas to the cost of L2 gas
uint256 public l2GasDiscountDivisor;
// The amount of L2 gas which can be forwarded to L2 without spam prevention via 'gas burn'.
// Calculated as the product of l2GasDiscountDivisor * enqueueGasCost.
// See comments in enqueue() for further detail.
uint256 public enqueueL2GasPrepaid;
// Encoding-related (all in bytes)
uint256 internal constant BATCH_CONTEXT_SIZE = 16;
uint256 internal constant BATCH_CONTEXT_LENGTH_POS = 12;
uint256 internal constant BATCH_CONTEXT_START_POS = 15;
uint256 internal constant TX_DATA_HEADER_SIZE = 3;
uint256 internal constant BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public maxTransactionGasLimit;
/***************
* Queue State *
***************/
uint40 private _nextQueueIndex; // index of the first queue element not yet included
Lib_OVMCodec.QueueElement[] queueElements;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _maxTransactionGasLimit,
uint256 _l2GasDiscountDivisor,
uint256 _enqueueGasCost
) Lib_AddressResolver(_libAddressManager) {
maxTransactionGasLimit = _maxTransactionGasLimit;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
enqueueGasCost = _enqueueGasCost;
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the Burn Admin may
* successfully call a method.
*/
modifier onlyBurnAdmin() {
require(
msg.sender == libAddressManager.owner(),
'Only callable by the Burn Admin.'
);
_;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external
onlyBurnAdmin
{
enqueueGasCost = _enqueueGasCost;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
// See the comment in enqueue() for the rationale behind this formula.
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
emit L2GasParamsUpdated(
l2GasDiscountDivisor,
enqueueGasCost,
enqueueL2GasPrepaid
);
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve('ChainStorageContainer-CTC-batches'));
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve('ChainStorageContainer-CTC-queue'));
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() public view returns (uint256 _totalElements) {
(uint40 totalElements, , , ) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() public view returns (uint256 _totalBatches) {
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() public view returns (uint40) {
return _nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() public view returns (uint40) {
(, , uint40 lastTimestamp, ) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() public view returns (uint40) {
(, , , uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
public
view
returns (Lib_OVMCodec.QueueElement memory _element)
{
return queueElements[_index];
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() public view returns (uint40) {
return uint40(queueElements.length) - _nextQueueIndex;
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() public view returns (uint40) {
return uint40(queueElements.length);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external {
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
'Transaction data size exceeds maximum for rollup transaction.'
);
require(
_gasLimit <= maxTransactionGasLimit,
'Transaction gas limit exceeds maximum for rollup transaction.'
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
'Transaction gas limit too low to enqueue.'
);
// Transactions submitted to the queue lack a method for paying gas fees to the Sequencer.
// So we need to prevent spam attacks by ensuring that the cost of enqueueing a transaction
// from L1 to L2 is not underpriced. For transaction with a high L2 gas limit, we do this by
// burning some extra gas on L1. Of course there is also some intrinsic cost to enqueueing a
// transaction, so we want to make sure not to over-charge (by burning too much L1 gas).
// Therefore, we define 'enqueueL2GasPrepaid' as the L2 gas limit above which we must burn
// additional gas on L1. This threshold is the product of two inputs:
// 1. enqueueGasCost: the base cost of calling this function.
// 2. l2GasDiscountDivisor: the ratio between the cost of gas on L1 and L2. This is a
// positive integer, meaning we assume L2 gas is always less costly.
// The calculation below for gasToConsume can be seen as converting the difference (between
// the specified L2 gas limit and the prepaid L2 gas limit) to an L1 gas amount.
if (_gasLimit > enqueueL2GasPrepaid) {
uint256 gasToConsume = (_gasLimit - enqueueL2GasPrepaid) /
l2GasDiscountDivisor;
uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed.
require(
startingGas > gasToConsume,
'Insufficient gas for L2 rate limiting burn.'
);
uint256 i;
while (startingGas - gasleft() < gasToConsume) {
i++;
}
}
// Apply an aliasing unless msg.sender == tx.origin. This prevents an attack in which a
// contract on L1 has the same address as a contract on L2 but doesn't have the same code.
// We can safely ignore this for EOAs because they're guaranteed to have the same "code"
// (i.e. no code at all). This also makes it possible for users to interact with contracts
// on L2 even when the Sequencer is down.
address sender;
if (msg.sender == tx.origin) {
sender = msg.sender;
} else {
sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender);
}
bytes32 transactionHash = keccak256(
abi.encode(sender, _target, _gasLimit, _data)
);
queueElements.push(
Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: uint40(block.timestamp),
blockNumber: uint40(block.number)
})
);
uint256 queueIndex = queueElements.length - 1;
emit TransactionEnqueued(
sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch() external {
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
'Actual batch start index does not match expected start index.'
);
require(
msg.sender == resolve('OVM_Sequencer'),
'Function can only be called by the Sequencer.'
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
'Not enough BatchContexts provided.'
);
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// Cache the _nextQueueIndex storage variable to a temporary stack variable.
// This is safe as long as nothing reads or writes to the storage variable
// until it is updated by the temp variable.
uint40 nextQueueIndex = _nextQueueIndex;
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
numSequencerTransactions += uint32(curContext.numSequencedTransactions);
// Now process any subsequent queue transactions.
nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions);
}
require(
nextQueueIndex <= queueElements.length,
'Attempted to append more elements than are available in the queue.'
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend -
numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = queueElements[
nextQueueIndex - 1
];
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// Cache the previous blockhash to ensure all transaction data can be retrieved efficiently.
_appendBatch(
blockhash(block.number - 1),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements()
);
// Update the _nextQueueIndex storage variable.
_nextQueueIndex = nextQueueIndex;
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(uint256 _index)
internal
pure
returns (BatchContext memory)
{
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(
232,
calldataload(add(contextPtr, 3))
)
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return
BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(
extraData,
0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
)
nextQueueIndex := shr(
40,
and(
extraData,
0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000
)
)
lastTimestamp := shr(
80,
and(
extraData,
0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000
)
)
lastBlockNumber := shr(
120,
and(
extraData,
0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000
)
)
}
// solhint-enable max-line-length
return (totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIdx Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIdx,
uint40 _timestamp,
uint40 _blockNumber
) internal pure returns (bytes27) {
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIdx))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
) internal {
IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec
.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex''
});
emit TransactionBatchAppended(
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.8.7;
library AddressAliasHelper {
uint160 constant offset = uint160(0x1111000000000000000000000000000000001111);
/// @notice Utility function that converts the address in the L1 that submitted a tx to
/// the inbox to the msg.sender viewed in the L2
/// @param l1Address the address in the L1 that triggered the tx to L2
/// @return l2Address L2 address as viewed in msg.sender
function applyL1ToL2Alias(address l1Address)
internal
pure
returns (address l2Address)
{
unchecked {
l2Address = address(uint160(l1Address) + offset);
}
}
/// @notice Utility function that converts the msg.sender viewed in the L2 to the
/// address in the L1 that submitted a tx to the inbox
/// @param l2Address L2 address as viewed in msg.sender
/// @return l1Address the address in the L1 that triggered the tx to L2
function undoL1ToL2Alias(address l2Address)
internal
pure
returns (address l1Address)
{
unchecked {
l1Address = address(uint160(l2Address) - offset);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {Lib_RLPReader} from '../rlp/Lib_RLPReader.sol';
import {Lib_RLPWriter} from '../rlp/Lib_RLPWriter.sol';
import {Lib_BytesUtils} from '../utils/Lib_BytesUtils.sol';
import {Lib_Bytes32Utils} from '../utils/Lib_Bytes32Utils.sol';
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction)
internal
pure
returns (bytes32)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded)
internal
pure
returns (EVMAccount memory)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(
_encoded
);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {Lib_AddressManager} from './Lib_AddressManager.sol';
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol';
/* Interface Imports */
import {IChainStorageContainer} from './IChainStorageContainer.sol';
/**
* @title ICanonicalTransactionChain
*/
interface ICanonicalTransactionChain {
/**********
* Events *
**********/
event L2GasParamsUpdated(
uint256 l2GasDiscountDivisor,
uint256 enqueueGasCost,
uint256 enqueueL2GasPrepaid
);
event TransactionEnqueued(
address indexed _l1TxOrigin,
address indexed _target,
uint256 _gasLimit,
bytes _data,
uint256 indexed _queueIndex,
uint256 _timestamp
);
event QueueBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event SequencerBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event TransactionBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
/***********
* Structs *
***********/
struct BatchContext {
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 timestamp;
uint256 blockNumber;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external;
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() external view returns (IChainStorageContainer);
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() external view returns (uint40);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
external
view
returns (Lib_OVMCodec.QueueElement memory _element);
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() external view returns (uint40);
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() external view returns (uint40);
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() external view returns (uint40);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() external view returns (uint40);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external;
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch(
// uint40 _shouldStartAtElement,
// uint24 _totalElementsToAppend,
// BatchContext[] _contexts,
// bytes[] _transactionDataFields
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({length: _in.length, ptr: ptr});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in)
internal
pure
returns (RLPItem[] memory)
{
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, 'Invalid RLP list value.');
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
'Provided RLP list exceeds max list length.'
);
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({length: _in.length - offset, ptr: _in.ptr + offset})
);
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes value.');
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in)
internal
pure
returns (string memory)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, 'Invalid RLP bytes32 value.');
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes32 value.');
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, 'Invalid RLP boolean value.');
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
'Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1'
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, 'Invalid RLP address value.');
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in)
internal
pure
returns (bytes memory)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, 'RLP item cannot be null.');
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, 'Invalid RLP short string.');
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, 'Invalid RLP long string length.');
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, 'Invalid RLP long string.');
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, 'Invalid RLP short list.');
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, 'Invalid RLP long list length.');
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, 'Invalid RLP long list.');
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset)
private
pure
returns (bytes memory)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start)
internal
pure
returns (bytes memory)
{
if (_start >= _bytes.length) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes)
internal
pure
returns (bytes memory)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other)
internal
pure
returns (bool)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* External Imports */
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// 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 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;
}
}
|
Retrieves the total number of batches submitted. return _totalBatches Total submitted batches./
|
function getTotalBatches() public view returns (uint256 _totalBatches) {
return batches().length();
}
| 1,596,296 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
}
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
}
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
if (totalBorrowsETH == 0) return uint256(0);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
// Pack the struct data
(uint[4] memory numData, address[6] memory cAddresses, bytes memory callData)
= _packData(_createInfo, _exchangeData);
bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
function _packData(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) {
numData = [
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
cAddresses = [
_createInfo.cCollAddress,
_createInfo.cBorrowAddress,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
callData = exchangeData.callData;
}
}
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
}
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CreamSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the cream position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
contract DFSExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract DFSPrices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers,
bytes[] memory _additionalData
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
}
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
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);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscriptions {
function unsubscribe() external virtual ;
}
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
abstract contract TokenInterface {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
}
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
contract MCDCreateTaker {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
contract MCDSaverProxyHelper is DSMath {
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
}
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getAccountBalances(
Account.Info memory account
) public view virtual returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function setOperators(
OperatorArg[] memory args
) public virtual;
function getNumMarkets() public view virtual returns (uint256);
function getMarketTokenAddress(uint256 marketId)
public
view
virtual
returns (address);
}
library Account {
// ============ Enums ============
/*
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum Status {
Normal,
Liquid,
Vapor
}
// ============ Structs ============
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
// The complete storage for any account
struct Storage {
mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
// ============ Library Functions ============
function equals(
Info memory a,
Info memory b
)
internal
pure
returns (bool)
{
return a.owner == b.owner && a.number == b.number;
}
}
library Actions {
// ============ Constants ============
bytes32 constant FILE = "Actions";
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {
OnePrimary,
TwoPrimary,
PrimaryAndSecondary
}
enum MarketLayout {
ZeroMarkets,
OneMarket,
TwoMarkets
}
// ============ Structs ============
/*
* Arguments that are passed to Solo in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
// ============ Action Types ============
/*
* Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply.
*/
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
/*
* Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount
* previously supplied.
*/
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
/*
* Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
* The amount field applies to accountOne.
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
/*
* Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
* applies to the makerMarket.
*/
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
* to the takerMarket.
*/
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Trades balances between two accounts using any external contract that implements the
* AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
* which it is trading on-behalf-of). The amount field applies to the makerAccount and the
* inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
* quote a change for the makerAccount in the outputMarket (or will disallow the trade).
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
/*
* Each account must maintain a certain margin-ratio (specified globally). If the account falls
* below this margin-ratio, it can be liquidated by any other account. This allows anyone else
* (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
* exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
* by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
* account also sets a flag on the account that the account is being liquidated. This allows
* anyone to continue liquidating the account until there are no more borrows being taken by the
* liquidating account. Liquidators do not have to liquidate the entire account all at once but
* can liquidate as much as they choose. The liquidating flag allows liquidators to continue
* liquidating the account even if it becomes collateralized through partial liquidation or
* price movement.
*/
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Similar to liquidate, but vaporAccounts are accounts that have only negative balances
* remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in
* exchange for a collateral asset (heldMarket) at a favorable spread. However, since the
* liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens.
*/
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Passes arbitrary bytes of data to an external contract that implements the Callee interface.
* Does not change any asset amounts. This function may be useful for setting certain variables
* on layer-two contracts for certain accounts without having to make a separate Ethereum
* transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
* from an operator of the particular account.
*/
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
// ============ Helper Functions ============
function getMarketLayout(
ActionType actionType
)
internal
pure
returns (MarketLayout)
{
if (
actionType == Actions.ActionType.Deposit
|| actionType == Actions.ActionType.Withdraw
|| actionType == Actions.ActionType.Transfer
) {
return MarketLayout.OneMarket;
}
else if (actionType == Actions.ActionType.Call) {
return MarketLayout.ZeroMarkets;
}
return MarketLayout.TwoMarkets;
}
function getAccountLayout(
ActionType actionType
)
internal
pure
returns (AccountLayout)
{
if (
actionType == Actions.ActionType.Transfer
|| actionType == Actions.ActionType.Trade
) {
return AccountLayout.TwoPrimary;
} else if (
actionType == Actions.ActionType.Liquidate
|| actionType == Actions.ActionType.Vaporize
) {
return AccountLayout.PrimaryAndSecondary;
}
return AccountLayout.OnePrimary;
}
// ============ Parsing Functions ============
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
{
assert(args.actionType == ActionType.Deposit);
return DepositArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
from: args.otherAddress
});
}
function parseWithdrawArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (WithdrawArgs memory)
{
assert(args.actionType == ActionType.Withdraw);
return WithdrawArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
to: args.otherAddress
});
}
function parseTransferArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TransferArgs memory)
{
assert(args.actionType == ActionType.Transfer);
return TransferArgs({
amount: args.amount,
accountOne: accounts[args.accountId],
accountTwo: accounts[args.otherAccountId],
market: args.primaryMarketId
});
}
function parseBuyArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (BuyArgs memory)
{
assert(args.actionType == ActionType.Buy);
return BuyArgs({
amount: args.amount,
account: accounts[args.accountId],
makerMarket: args.primaryMarketId,
takerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseSellArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (SellArgs memory)
{
assert(args.actionType == ActionType.Sell);
return SellArgs({
amount: args.amount,
account: accounts[args.accountId],
takerMarket: args.primaryMarketId,
makerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseTradeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TradeArgs memory)
{
assert(args.actionType == ActionType.Trade);
return TradeArgs({
amount: args.amount,
takerAccount: accounts[args.accountId],
makerAccount: accounts[args.otherAccountId],
inputMarket: args.primaryMarketId,
outputMarket: args.secondaryMarketId,
autoTrader: args.otherAddress,
tradeData: args.data
});
}
function parseLiquidateArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (LiquidateArgs memory)
{
assert(args.actionType == ActionType.Liquidate);
return LiquidateArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
liquidAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseVaporizeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (VaporizeArgs memory)
{
assert(args.actionType == ActionType.Vaporize);
return VaporizeArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
vaporAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseCallArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (CallArgs memory)
{
assert(args.actionType == ActionType.Call);
return CallArgs({
account: accounts[args.accountId],
callee: args.otherAddress,
data: args.data
});
}
}
library Math {
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Math";
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint128"
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint96"
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint32"
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
library Types {
using Math for uint256;
// ============ AssetAmount ============
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;
}
// ============ Par (Principal Amount) ============
// Total borrow and supply values for a market
struct TotalPar {
uint128 borrow;
uint128 supply;
}
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
function zeroWei()
internal
pure
returns (Wei memory)
{
return Wei({
sign: false,
value: 0
});
}
function sub(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
return add(a, negative(b));
}
function add(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
Wei memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value);
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value);
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value);
}
}
return result;
}
function equals(
Wei memory a,
Wei memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Wei memory a
)
internal
pure
returns (Wei memory)
{
return Wei({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Wei memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Wei memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Wei memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// 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);
}
}
}
}
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
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: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
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: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
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: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 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(ERC20 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));
}
function _callOptionalReturn(ERC20 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");
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for variable rate and 2 for fixed rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
if (originationFee > 0) {
ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee);
}
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 19;
uint public BOOST_GAS_TOKEN = 19;
uint public MAX_GAS_PRICE = 200000000000; // 200 gwei
uint public REPAY_GAS_COST = 2500000;
uint public BOOST_GAS_COST = 2500000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address user,
address proxy
)
= abi.decode(data, (address,address,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
}
// pull tokens from user to proxy
ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x7b856af5753a9f80968EA002641E69AdF1d795aB;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve AaveImport to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
contract CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint) {
uint compBalance = 0;
for(uint i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) {
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta);
}
function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) {
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta);
}
}
}
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CompoundImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, 0);
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay compound debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the cream protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the cream protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the cream protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the cream market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the cream market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CreamLoanInfo is CreamSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches cream prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches cream collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay cream debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return address(this).balance;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (_exData.srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
}
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.offchainData.callData, 36, _exData.destAmount);
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
if (success) {
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1800000;
uint public BOOST_GAS_COST = 1800000;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
closeCDP(closeData, exchangeData, user);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user
) internal {
paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = _closeData.daiAmount;
(, daiSwaped) = _buy(_exchangeData);
}
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
manager.frob(_cdpId, -toPositiveInt(_amount), 0);
manager.flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = manager.urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDCloseTaker is MCDSaverProxyHelper {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
manager.urns(_closeData.cdpId),
manager.urns(_closeData.cdpId),
manager.ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId));
}
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public constant manager = Manager(MANAGER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(_cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(_cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(manager.urns(_cdpId));
uint maxAmount = getMaxDebt(_cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
manager.move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
manager.ilks(_cdpId),
manager.urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
manager.frob(_cdpId, -toPositiveInt(frobAmount), 0);
manager.flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = manager.urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) {
address urn = manager.urns(_cdpId);
ilk = manager.ilks(_cdpId);
(collateral, debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
price = getPrice(ilk);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (feeAmount > _amount / 10) {
feeAmount = _amount / 10;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
return feeAmount;
}
return 0;
}
}
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (isEthJoinAddr(_joinAddr)
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth {
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
if (paramData.swapType == 1) { // COLL_SWAP
exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) { // DEBT_SWAP
exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy);
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)));
} else { // NO_SWAP just send tokens to proxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr));
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(uint _amount, uint _fee, bytes memory _params)
internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) {
(
uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x
address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper
uint8[3] memory enumData, // fromProtocol, toProtocol, swapType
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address));
bytes memory proxyData1;
bytes memory proxyData2;
uint openDebtAmount = (_amount + _fee);
if (enumData[0] == 0) { // MAKER FROM
proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]);
} else if(enumData[0] == 1) { // COMPOUND FROM
if (enumData[2] == 2) { // DEBT_SWAP
proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]);
} else {
proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]);
}
}
if (enumData[1] == 0) { // MAKER TO
proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount);
} else if(enumData[1] == 1) { // COMPOUND TO
if (enumData[2] == 2) { // DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]);
} else {
proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: addrData[2],
protocol1: enumData[0],
protocol2: enumData[1],
swapType: enumData[2]
});
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: addrData[4],
destAddr: addrData[5],
srcAmount: numData[4],
destAmount: numData[5],
minPrice: numData[6],
wrapper: addrData[7],
exchangeAddr: addrData[6],
callData: callData,
price0x: numData[7]
});
}
function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxyInterface proxy = DSProxyInterface(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
(
uint[8] memory numData,
address[8] memory addrData,
uint8[3] memory enumData,
bytes memory callData
)
= _packData(_loanShift, _exchangeData);
// encode data
bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return CTokenInterface(_address).underlying();
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function logEvent(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
function _packData(
LoanShiftData memory _loanShift,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) {
numData = [
_loanShift.collAmount,
_loanShift.debtAmount,
_loanShift.id1,
_loanShift.id2,
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
addrData = [
_loanShift.addrLoan1,
_loanShift.addrLoan2,
_loanShift.debtAddr1,
_loanShift.debtAddr2,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
enumData = [
uint8(_loanShift.fromProtocol),
uint8(_loanShift.toProtocol),
uint8(_loanShift.swapType)
];
callData = exchangeData.callData;
}
}
contract CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
contract McdShifter is MCDSaverProxy {
using SafeERC20 for ERC20;
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(_cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawCollateral(_cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(_cdpId, _joinAddr, collAmount);
// draw debt
drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
}
contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
// swap
(, destAmount) = _sell(_data);
destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr);
// swap
(, destAmount) = _sell(_data);
} else {
_data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr);
destAmount = _data.srcAmount;
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
(, uint sellAmount) = _sell(exchangeData);
getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
(
uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x
address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[4],address[6],bytes,address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
cAddresses[0], cAddresses[1], (_amount + _fee));
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: cAddresses[2],
destAddr: cAddresses[3],
srcAmount: numData[0],
destAmount: numData[1],
minPrice: numData[2],
wrapper: cAddresses[5],
exchangeAddr: cAddresses[4],
callData: callData,
price0x: numData[3]
});
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: cAddresses[0],
cDebtAddr: cAddresses[1]
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxy proxy = DSProxy(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.srcAmount = collAmount;
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId));
uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
bytes32 ilk = manager.ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(_saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
|
check if cdp is subscribed check if boost and boost allowed
|
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
if (!subscribed) return (false, 0);
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
return (currRatio > holder.maxRatio, currRatio);
}
}
| 7,333,797 |
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `index` >= `totalSupply()`.
/// @param index A counter less than `totalSupply()`
/// @return The token identifier for the `index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `index` >= `balanceOf(owner)` or if
/// `owner` is the zero address, representing invalid NFTs.
/// @param owner An address where we are interested in NFTs owned by them
/// @param index A counter less than `balanceOf(owner)`
/// @return The token identifier for the `index`th NFT assigned to `owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
}
|
ERC-721 Non-Fungible Token Standard, optional enumeration extension See https://eips.ethereum.org/EIPS/eip-721 Note: the ERC-165 identifier for this interface is 0x780e9d63.
|
interface ERC721Enumerable /* is ERC721 */ {
function totalSupply() external view returns (uint256);
function tokenByIndex(uint256 index) external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
pragma solidity ^0.8.4;
}
| 1,021,544 |
// SPDX-License-Identifier: Apache2.0
pragma solidity ^0.8.0;
contract CharityDonation{
// ethereum address of contract owner
address payable contractOwner;
// list of charities (by address) this contract supports
address payable[] private supportedCharities;
// variable to store total number of donations
uint private totalDonations;
// variables to store top donor info
uint private topDonation;
address private topDonor;
// constructor to initialize contract owner, supported charities and init total donations sum
constructor(address payable[] memory charities) {
contractOwner = payable(msg.sender);
supportedCharities = charities;
totalDonations = 0;
}
/// modifier to prerequisite contract onwer only access to some methods
modifier ownerOnly {
require(msg.sender == contractOwner);
_;
}
/// define donation event
event DonationEvent(address donor, uint donationAmount);
/* Contract level methods */
/// view function to check if charity input is valid
function verifyCharityID(uint8 inputCharityID) private view {
require(inputCharityID >= 0 && inputCharityID < supportedCharities.length, "Input charity ID is invalid");
}
/// checks if sender address has sufficient funds to send
function checkIfFundsExist(uint userBalance, uint amountToSend) private pure {
require(userBalance >= amountToSend, "Check if user has the amount of ETH specified to send");
}
/// checks if current donation is bigger than the previous top one and alters info
function alterTopDonor(uint currentDonationAmount, uint _topDonation) private {
if (_topDonation < currentDonationAmount) {
topDonation = currentDonationAmount;
topDonor = msg.sender;
}
}
/// increase total donations amount
function increaseDonationTotal(uint amountDonated) private {
totalDonations = totalDonations + amountDonated;
}
/// sends donation (funds) to charity and destination address and emits a donation event
function makeTransactions(uint amountToDonate, address payable destinationAddress, uint amountToSend, uint8 charityID) private {
supportedCharities[charityID].transfer(amountToDonate);
destinationAddress.transfer(amountToSend);
// emit donation event when transfers are made
emit DonationEvent(msg.sender, amountToDonate);
}
/* Publicly accessible methods */
// variation A that sends 10% as a donation to a selected charity
function sendFunds(address payable destinationAddress, uint8 charityID) public payable{
verifyCharityID(charityID);
checkIfFundsExist(msg.sender.balance, msg.value);
// donation strategy (10%)
uint amountToDonate = msg.value / 10;
uint amountToSend = msg.value - amountToDonate;
alterTopDonor(amountToDonate, topDonation);
increaseDonationTotal(amountToDonate);
makeTransactions(amountToDonate, destinationAddress, amountToSend, charityID);
}
// variation B that sends specified donation amount to a selected charity
function sendFunds(address payable destinationAddress, uint8 charityID, uint amountToDonate) public payable{
verifyCharityID(charityID);
checkIfFundsExist(msg.sender.balance, msg.value);
// donation strategy (specific amount)
require(amountToDonate >= msg.value/100 && amountToDonate <= msg.value/2, "Donation amount must be at least 1% and at most 50% of the amount send");
uint amountToSend = msg.value - amountToDonate;
alterTopDonor(amountToDonate, topDonation);
increaseDonationTotal(amountToDonate);
makeTransactions(amountToDonate, destinationAddress, amountToSend, charityID);
}
// function to view total sum of donations made to all charities
function getOverallDonationInfo() public view returns (uint) {
return totalDonations;
}
/* Methods accesible only from contract owner */
// Get top donation amount and who made it
function getTopDonation() public ownerOnly view returns (uint, address) {
return (topDonation, topDonor);
}
// destroy contract and send all funds attached, to the contract owner
function destroyContract() public ownerOnly {
selfdestruct(contractOwner);
}
}
|
sends donation (funds) to charity and destination address and emits a donation event emit donation event when transfers are made
|
function makeTransactions(uint amountToDonate, address payable destinationAddress, uint amountToSend, uint8 charityID) private {
supportedCharities[charityID].transfer(amountToDonate);
destinationAddress.transfer(amountToSend);
emit DonationEvent(msg.sender, amountToDonate);
}
| 6,413,830 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
//import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
//import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol";
//import "../interfaces/IStakeRegistry.sol";
import "../interfaces/IStakeUniswapV3.sol";
import "../interfaces/IAutoRefactorCoinageWithTokenId.sol";
import "../interfaces/IIStake2Vault.sol";
import {DSMath} from "../libraries/DSMath.sol";
import "../common/AccessibleCommon.sol";
import "../stake/StakeUniswapV3Storage.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/SafeMath32.sol";
/// @title StakeUniswapV3
/// @notice Uniswap V3 Contract for staking LP and mining TOS
contract StakeUniswapV3 is
StakeUniswapV3Storage,
AccessibleCommon,
IStakeUniswapV3,
DSMath
{
using SafeMath for uint256;
using SafeMath32 for uint32;
struct PositionInfo {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
// the fees owed to the position owner in token0/token1
uint128 tokensOwed0;
uint128 tokensOwed1;
}
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the most-recently updated index of the observations array
uint16 observationIndex;
// the current maximum number of observations that are being stored
uint16 observationCardinality;
// the next maximum number of observations to store, triggered in observations.write
uint16 observationCardinalityNext;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
// whether the pool is locked
bool unlocked;
}
/// @dev event on staking
/// @param to the sender
/// @param poolAddress the pool address of uniswapV3
/// @param tokenId the uniswapV3 Lp token
/// @param amount the amount of staking
event Staked(
address indexed to,
address indexed poolAddress,
uint256 tokenId,
uint256 amount
);
/// @dev event on claim
/// @param to the sender
/// @param poolAddress the pool address of uniswapV3
/// @param tokenId the uniswapV3 Lp token
/// @param miningAmount the amount of mining
/// @param nonMiningAmount the amount of non-mining
event Claimed(
address indexed to,
address poolAddress,
uint256 tokenId,
uint256 miningAmount,
uint256 nonMiningAmount
);
/// @dev event on withdrawal
/// @param to the sender
/// @param tokenId the uniswapV3 Lp token
/// @param miningAmount the amount of mining
/// @param nonMiningAmount the amount of non-mining
event WithdrawalToken(
address indexed to,
uint256 tokenId,
uint256 miningAmount,
uint256 nonMiningAmount
);
/// @dev event on mining in coinage
/// @param curTime the current time
/// @param miningInterval mining period (sec)
/// @param miningAmount the mining amount
/// @param prevTotalSupply Total amount of coinage before mining
/// @param afterTotalSupply Total amount of coinage after being mined
/// @param factor coinage's Factor
event MinedCoinage(
uint256 curTime,
uint256 miningInterval,
uint256 miningAmount,
uint256 prevTotalSupply,
uint256 afterTotalSupply,
uint256 factor
);
/// @dev event on burning in coinage
/// @param curTime the current time
/// @param tokenId the token id
/// @param burningAmount the buring amount
/// @param prevTotalSupply Total amount of coinage before mining
/// @param afterTotalSupply Total amount of coinage after being mined
event BurnedCoinage(
uint256 curTime,
uint256 tokenId,
uint256 burningAmount,
uint256 prevTotalSupply,
uint256 afterTotalSupply
);
/// @dev constructor of StakeCoinage
constructor() {
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(ADMIN_ROLE, msg.sender);
miningIntervalSeconds = 15;
}
/// @dev receive ether - revert
receive() external payable {
revert();
}
/// @dev Mining interval setting (seconds)
/// @param _intervalSeconds the mining interval (sec)
function setMiningIntervalSeconds(uint256 _intervalSeconds)
external
onlyOwner
{
miningIntervalSeconds = _intervalSeconds;
}
/// @dev reset coinage's last mining time variable for tes
function resetCoinageTime() external onlyOwner {
coinageLastMintBlockTimetamp = 0;
}
/// @dev set sale start time
/// @param _saleStartTime sale start time
function setSaleStartTime(uint256 _saleStartTime) external onlyOwner {
require(
_saleStartTime > 0 && saleStartTime != _saleStartTime,
"StakeUniswapV3: zero or same _saleStartTime"
);
saleStartTime = _saleStartTime;
}
/// @dev calculate the factor of coinage
/// @param source tsource
/// @param target target
/// @param oldFactor oldFactor
function _calcNewFactor(
uint256 source,
uint256 target,
uint256 oldFactor
) internal pure returns (uint256) {
return rdiv(rmul(target, oldFactor), source);
}
/// @dev delete user's token storage of index place
/// @param _owner tokenId's owner
/// @param tokenId tokenId
/// @param _index owner's tokenId's index
function deleteUserToken(
address _owner,
uint256 tokenId,
uint256 _index
) internal {
uint256 _tokenid = userStakedTokenIds[_owner][_index];
require(_tokenid == tokenId, "StakeUniswapV3: mismatch token");
uint256 lastIndex = (userStakedTokenIds[_owner].length).sub(1);
if (tokenId > 0 && _tokenid == tokenId) {
if (_index < lastIndex) {
uint256 tokenId_lastIndex =
userStakedTokenIds[_owner][lastIndex];
userStakedTokenIds[_owner][_index] = tokenId_lastIndex;
depositTokens[tokenId_lastIndex].idIndex = _index;
}
userStakedTokenIds[_owner].pop();
}
}
/// @dev mining on coinage, Mining conditions : the sale start time must pass,
/// the stake start time must pass, the vault mining start time (sale start time) passes,
/// the mining interval passes, and the current total amount is not zero,
function miningCoinage() public lock {
if (saleStartTime == 0 || saleStartTime > block.timestamp) return;
if (stakeStartTime == 0 || stakeStartTime > block.timestamp) return;
if (
IIStake2Vault(vault).miningStartTime() > block.timestamp ||
IIStake2Vault(vault).miningEndTime() < block.timestamp
) return;
if (coinageLastMintBlockTimetamp == 0)
coinageLastMintBlockTimetamp = stakeStartTime;
if (
block.timestamp >
(coinageLastMintBlockTimetamp.add(miningIntervalSeconds))
) {
uint256 miningInterval =
block.timestamp.sub(coinageLastMintBlockTimetamp);
uint256 miningAmount =
miningInterval.mul(IIStake2Vault(vault).miningPerSecond());
uint256 prevTotalSupply =
IAutoRefactorCoinageWithTokenId(coinage).totalSupply();
if (miningAmount > 0 && prevTotalSupply > 0) {
uint256 afterTotalSupply =
prevTotalSupply.add(miningAmount.mul(10**9));
uint256 factor =
IAutoRefactorCoinageWithTokenId(coinage).setFactor(
_calcNewFactor(
prevTotalSupply,
afterTotalSupply,
IAutoRefactorCoinageWithTokenId(coinage).factor()
)
);
coinageLastMintBlockTimetamp = block.timestamp;
emit MinedCoinage(
block.timestamp,
miningInterval,
miningAmount,
prevTotalSupply,
afterTotalSupply,
factor
);
}
}
}
/// @dev view mining information of tokenId
/// @param tokenId tokenId
function getMiningTokenId(uint256 tokenId)
public
view
override
nonZeroAddress(poolAddress)
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint160 secondsInside,
uint256 secondsInsideDiff256,
uint256 liquidity,
uint256 balanceOfTokenIdRay,
uint256 minableAmountRay,
uint256 secondsInside256,
uint256 secondsAbsolute256
)
{
if (
stakeStartTime < block.timestamp && stakeStartTime < block.timestamp
) {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
liquidity = _depositTokens.liquidity;
uint32 secondsAbsolute = 0;
balanceOfTokenIdRay = IAutoRefactorCoinageWithTokenId(coinage)
.balanceOf(tokenId);
if (_depositTokens.liquidity > 0 && balanceOfTokenIdRay > 0) {
if (balanceOfTokenIdRay > liquidity.mul(10**9)) {
minableAmountRay = balanceOfTokenIdRay.sub(
liquidity.mul(10**9)
);
minableAmount = minableAmountRay.div(10**9);
}
if (minableAmount > 0) {
(, , secondsInside) = IUniswapV3Pool(poolAddress)
.snapshotCumulativesInside(
_depositTokens.tickLower,
_depositTokens.tickUpper
);
secondsInside256 = uint256(secondsInside);
if (_depositTokens.claimedTime > 0)
secondsAbsolute = uint32(block.timestamp).sub(
_depositTokens.claimedTime
);
else
secondsAbsolute = uint32(block.timestamp).sub(
_depositTokens.startTime
);
secondsAbsolute256 = uint256(secondsAbsolute);
if (secondsAbsolute > 0) {
if (_depositTokens.secondsInsideLast > 0) {
secondsInsideDiff256 = secondsInside256.sub(
uint256(_depositTokens.secondsInsideLast)
);
} else {
secondsInsideDiff256 = secondsInside256.sub(
uint256(_depositTokens.secondsInsideInitial)
);
}
if (
secondsInsideDiff256 < secondsAbsolute256 &&
secondsInsideDiff256 > 0
) {
miningAmount = minableAmount
.mul(secondsInsideDiff256)
.div(secondsAbsolute256);
nonMiningAmount = minableAmount.sub(miningAmount);
} else if(secondsInsideDiff256 > 0){
miningAmount = minableAmount;
} else {
nonMiningAmount = minableAmount;
}
}
}
}
}
}
/// @dev With the given tokenId, information is retrieved from nonfungiblePositionManager,
/// and the pool address is calculated and set.
/// @param tokenId tokenId
function setPoolAddress(uint256 tokenId)
external
onlyOwner
nonZeroAddress(token)
nonZeroAddress(vault)
nonZeroAddress(stakeRegistry)
nonZeroAddress(poolToken0)
nonZeroAddress(poolToken1)
nonZeroAddress(address(nonfungiblePositionManager))
nonZeroAddress(uniswapV3FactoryAddress)
{
require(poolAddress == address(0), "StakeUniswapV3: already set");
(, , address token0, address token1, uint24 fee, , , , , , , ) =
nonfungiblePositionManager.positions(tokenId);
require(
(token0 == poolToken0 && token1 == poolToken1) ||
(token0 == poolToken1 && token1 == poolToken0),
"StakeUniswapV3: different token"
);
poolToken0 = token0;
poolToken1 = token1;
poolAddress = PoolAddress.computeAddress(
uniswapV3FactoryAddress,
PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee})
);
poolFee = fee;
}
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
/// @param deadline the deadline that valid the owner's signature
/// @param v the owner's signature - v
/// @param r the owner's signature - r
/// @param s the owner's signature - s
function stakePermit(
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
override
nonZeroAddress(token)
nonZeroAddress(vault)
nonZeroAddress(stakeRegistry)
nonZeroAddress(poolToken0)
nonZeroAddress(poolToken1)
nonZeroAddress(address(nonfungiblePositionManager))
nonZeroAddress(uniswapV3FactoryAddress)
{
require(
saleStartTime < block.timestamp,
"StakeUniswapV3: before start"
);
require(
block.timestamp < IIStake2Vault(vault).miningEndTime(),
"StakeUniswapV3: end mining"
);
require(
nonfungiblePositionManager.ownerOf(tokenId) == msg.sender,
"StakeUniswapV3: not owner"
);
nonfungiblePositionManager.permit(
address(this),
tokenId,
deadline,
v,
r,
s
);
_stake(tokenId);
}
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
function stake(uint256 tokenId)
external
override
nonZeroAddress(token)
nonZeroAddress(vault)
nonZeroAddress(stakeRegistry)
nonZeroAddress(poolToken0)
nonZeroAddress(poolToken1)
nonZeroAddress(address(nonfungiblePositionManager))
nonZeroAddress(uniswapV3FactoryAddress)
{
require(
saleStartTime < block.timestamp,
"StakeUniswapV3: before start"
);
require(
block.timestamp < IIStake2Vault(vault).miningEndTime(),
"StakeUniswapV3: end mining"
);
require(
nonfungiblePositionManager.ownerOf(tokenId) == msg.sender,
"StakeUniswapV3: not owner"
);
_stake(tokenId);
}
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
function _stake(uint256 tokenId) internal {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
require(
_depositTokens.owner == address(0),
"StakeUniswapV3: Already staked"
);
uint256 _tokenId = tokenId;
(
,
,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = nonfungiblePositionManager.positions(_tokenId);
require(
(token0 == poolToken0 && token1 == poolToken1) ||
(token0 == poolToken1 && token1 == poolToken0),
"StakeUniswapV3: different token"
);
require(liquidity > 0, "StakeUniswapV3: zero liquidity");
if (poolAddress == address(0)) {
poolAddress = PoolAddress.computeAddress(
uniswapV3FactoryAddress,
PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee})
);
}
require(poolAddress != address(0), "StakeUniswapV3: zero poolAddress");
(, int24 tick, , , , , bool unlocked) =
IUniswapV3Pool(poolAddress).slot0();
require(unlocked, "StakeUniswapV3: unlocked pool");
require(
tickLower < tick && tick < tickUpper,
"StakeUniswapV3: out of tick range"
);
(, , uint32 secondsInside) =
IUniswapV3Pool(poolAddress).snapshotCumulativesInside(
tickLower,
tickUpper
);
uint256 tokenId_ = _tokenId;
// initial start time
if (stakeStartTime == 0) stakeStartTime = block.timestamp;
_depositTokens.owner = msg.sender;
_depositTokens.idIndex = userStakedTokenIds[msg.sender].length;
_depositTokens.liquidity = liquidity;
_depositTokens.tickLower = tickLower;
_depositTokens.tickUpper = tickUpper;
_depositTokens.startTime = uint32(block.timestamp);
_depositTokens.claimedTime = 0;
_depositTokens.secondsInsideInitial = secondsInside;
_depositTokens.secondsInsideLast = 0;
nonfungiblePositionManager.transferFrom(
msg.sender,
address(this),
tokenId_
);
// save tokenid
userStakedTokenIds[msg.sender].push(tokenId_);
totalStakedAmount = totalStakedAmount.add(liquidity);
totalTokens = totalTokens.add(1);
LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked =
userTotalStaked[msg.sender];
if (!_userTotalStaked.staked) totalStakers = totalStakers.add(1);
_userTotalStaked.staked = true;
_userTotalStaked.totalDepositAmount = _userTotalStaked
.totalDepositAmount
.add(liquidity);
LibUniswapV3Stake.StakedTokenAmount storage _stakedCoinageTokens =
stakedCoinageTokens[tokenId_];
_stakedCoinageTokens.amount = liquidity;
_stakedCoinageTokens.startTime = uint32(block.timestamp);
//mint coinage of user amount
IAutoRefactorCoinageWithTokenId(coinage).mint(
msg.sender,
tokenId_,
uint256(liquidity).mul(10**9)
);
miningCoinage();
emit Staked(msg.sender, poolAddress, tokenId_, liquidity);
}
/// @dev The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function claim(uint256 tokenId) external override {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
require(
_depositTokens.owner == msg.sender,
"StakeUniswapV3: not staker"
);
require(
_depositTokens.claimedTime <
uint32(block.timestamp.sub(miningIntervalSeconds)),
"StakeUniswapV3: already claimed"
);
require(_depositTokens.claimLock == false, "StakeUniswapV3: claiming");
_depositTokens.claimLock = true;
miningCoinage();
(
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint160 secondsInside,
,
,
,
uint256 minableAmountRay,
,
) = getMiningTokenId(tokenId);
require(miningAmount > 0, "StakeUniswapV3: zero miningAmount");
_depositTokens.claimedTime = uint32(block.timestamp);
_depositTokens.secondsInsideLast = secondsInside;
IAutoRefactorCoinageWithTokenId(coinage).burn(
msg.sender,
tokenId,
minableAmountRay
);
// storage stakedCoinageTokens
LibUniswapV3Stake.StakedTokenAmount storage _stakedCoinageTokens =
stakedCoinageTokens[tokenId];
_stakedCoinageTokens.claimedTime = uint32(block.timestamp);
_stakedCoinageTokens.claimedAmount = _stakedCoinageTokens
.claimedAmount
.add(miningAmount);
_stakedCoinageTokens.nonMiningAmount = _stakedCoinageTokens
.nonMiningAmount
.add(nonMiningAmount);
// storage StakedTotalTokenAmount
LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked =
userTotalStaked[msg.sender];
_userTotalStaked.totalMiningAmount = _userTotalStaked
.totalMiningAmount
.add(miningAmount);
_userTotalStaked.totalNonMiningAmount = _userTotalStaked
.totalNonMiningAmount
.add(nonMiningAmount);
// total
miningAmountTotal = miningAmountTotal.add(miningAmount);
nonMiningAmountTotal = nonMiningAmountTotal.add(nonMiningAmount);
require(
IIStake2Vault(vault).claimMining(
msg.sender,
minableAmount,
miningAmount,
nonMiningAmount
)
);
_depositTokens.claimLock = false;
emit Claimed(
msg.sender,
poolAddress,
tokenId,
miningAmount,
nonMiningAmount
);
}
/// @dev withdraw the deposited token.
/// The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function withdraw(uint256 tokenId) external override {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
require(
_depositTokens.owner == msg.sender,
"StakeUniswapV3: not staker"
);
require(
_depositTokens.withdraw == false,
"StakeUniswapV3: withdrawing"
);
_depositTokens.withdraw = true;
miningCoinage();
if (totalStakedAmount >= _depositTokens.liquidity)
totalStakedAmount = totalStakedAmount.sub(_depositTokens.liquidity);
if (totalTokens > 0) totalTokens = totalTokens.sub(1);
(
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
,
,
,
,
,
,
) = getMiningTokenId(tokenId);
IAutoRefactorCoinageWithTokenId(coinage).burnTokenId(
msg.sender,
tokenId
);
// storage StakedTotalTokenAmount
LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked =
userTotalStaked[msg.sender];
_userTotalStaked.totalDepositAmount = _userTotalStaked
.totalDepositAmount
.sub(_depositTokens.liquidity);
_userTotalStaked.totalMiningAmount = _userTotalStaked
.totalMiningAmount
.add(miningAmount);
_userTotalStaked.totalNonMiningAmount = _userTotalStaked
.totalNonMiningAmount
.add(nonMiningAmount);
// total
miningAmountTotal = miningAmountTotal.add(miningAmount);
nonMiningAmountTotal = nonMiningAmountTotal.add(nonMiningAmount);
deleteUserToken(_depositTokens.owner, tokenId, _depositTokens.idIndex);
delete depositTokens[tokenId];
delete stakedCoinageTokens[tokenId];
if (_userTotalStaked.totalDepositAmount == 0) {
totalStakers = totalStakers.sub(1);
delete userTotalStaked[msg.sender];
}
if (minableAmount > 0)
require(
IIStake2Vault(vault).claimMining(
msg.sender,
minableAmount,
miningAmount,
nonMiningAmount
)
);
nonfungiblePositionManager.safeTransferFrom(
address(this),
msg.sender,
tokenId
);
emit WithdrawalToken(
msg.sender,
tokenId,
miningAmount,
nonMiningAmount
);
}
/// @dev Get the list of staked tokens of the user
/// @param user user address
function getUserStakedTokenIds(address user)
external
view
override
returns (uint256[] memory ids)
{
return userStakedTokenIds[user];
}
/// @dev tokenId's deposited information
/// @param tokenId tokenId
/// @return _poolAddress poolAddress
/// @return tick tick,
/// @return liquidity liquidity,
/// @return args liquidity, startTime, claimedTime, startBlock, claimedBlock, claimedAmount
/// @return secondsPL secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128Las
function getDepositToken(uint256 tokenId)
external
view
override
returns (
address _poolAddress,
int24[2] memory tick,
uint128 liquidity,
uint256[5] memory args,
uint160[2] memory secondsPL
)
{
LibUniswapV3Stake.StakeLiquidity memory _depositTokens =
depositTokens[tokenId];
LibUniswapV3Stake.StakedTokenAmount memory _stakedCoinageTokens =
stakedCoinageTokens[tokenId];
return (
poolAddress,
[_depositTokens.tickLower, _depositTokens.tickUpper],
_depositTokens.liquidity,
[
_depositTokens.startTime,
_depositTokens.claimedTime,
_stakedCoinageTokens.startTime,
_stakedCoinageTokens.claimedTime,
_stakedCoinageTokens.claimedAmount
],
[
_depositTokens.secondsInsideInitial,
_depositTokens.secondsInsideLast
]
);
}
/// @dev user's staked total infos
/// @param user user address
/// @return totalDepositAmount total deposited amount
/// @return totalMiningAmount total mining amount ,
/// @return totalNonMiningAmount total non-mining amount,
function getUserStakedTotal(address user)
external
view
override
returns (
uint256 totalDepositAmount,
uint256 totalMiningAmount,
uint256 totalNonMiningAmount
)
{
return (
userTotalStaked[user].totalDepositAmount,
userTotalStaked[user].totalMiningAmount,
userTotalStaked[user].totalNonMiningAmount
);
}
/// @dev totalSupply of coinage
function totalSupplyCoinage() external view returns (uint256) {
return IAutoRefactorCoinageWithTokenId(coinage).totalSupply();
}
/// @dev balanceOf of tokenId's coinage
function balanceOfCoinage(uint256 tokenId) external view returns (uint256) {
return IAutoRefactorCoinageWithTokenId(coinage).balanceOf(tokenId);
}
/// @dev Give the infomation of this stakeContracts
/// @return return1 [token, vault, stakeRegistry, coinage]
/// @return return2 [poolToken0, poolToken1, nonfungiblePositionManager, uniswapV3FactoryAddress]
/// @return return3 [totalStakers, totalStakedAmount, miningAmountTotal,nonMiningAmountTotal]
function infos()
external
view
override
returns (
address[4] memory,
address[4] memory,
uint256[4] memory
)
{
return (
[token, vault, stakeRegistry, coinage],
[
poolToken0,
poolToken1,
address(nonfungiblePositionManager),
uniswapV3FactoryAddress
],
[
totalStakers,
totalStakedAmount,
miningAmountTotal,
nonMiningAmountTotal
]
);
}
/*
/// @dev pool's infos
/// @return factory pool's factory address
/// @return token0 token0 address
/// @return token1 token1 address
/// @return fee fee
/// @return tickSpacing tickSpacing
/// @return maxLiquidityPerTick maxLiquidityPerTick
/// @return liquidity pool's liquidity
function poolInfos()
external
view
override
nonZeroAddress(poolAddress)
returns (
address factory,
address token0,
address token1,
uint24 fee,
int24 tickSpacing,
uint128 maxLiquidityPerTick,
uint128 liquidity
)
{
liquidity = IUniswapV3Pool(poolAddress).liquidity();
factory = IUniswapV3Pool(poolAddress).factory();
token0 = IUniswapV3Pool(poolAddress).token0();
token1 = IUniswapV3Pool(poolAddress).token1();
fee = IUniswapV3Pool(poolAddress).fee();
tickSpacing = IUniswapV3Pool(poolAddress).tickSpacing();
maxLiquidityPerTick = IUniswapV3Pool(poolAddress).maxLiquidityPerTick();
}
*/
/*
/// @dev key's info
/// @param key hash(owner, tickLower, tickUpper)
/// @return _liquidity key's liquidity
/// @return feeGrowthInside0LastX128 key's feeGrowthInside0LastX128
/// @return feeGrowthInside1LastX128 key's feeGrowthInside1LastX128
/// @return tokensOwed0 key's tokensOwed0
/// @return tokensOwed1 key's tokensOwed1
function poolPositions(bytes32 key)
external
view
override
nonZeroAddress(poolAddress)
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
(
_liquidity,
feeGrowthInside0LastX128,
feeGrowthInside1LastX128,
tokensOwed0,
tokensOwed1
) = IUniswapV3Pool(poolAddress).positions(key);
}
*/
/// @dev pool's slot0 (current position)
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool
/// @return unlocked Whether the pool is currently locked to reentrancy
function poolSlot0()
external
view
override
nonZeroAddress(poolAddress)
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
)
{
(
sqrtPriceX96,
tick,
observationIndex,
observationCardinality,
observationCardinalityNext,
feeProtocol,
unlocked
) = IUniswapV3Pool(poolAddress).slot0();
}
/*
/// @dev _tokenId's position
/// @param _tokenId tokenId
/// @return nonce the nonce for permits
/// @return operator the address that is approved for spending this token
/// @return token0 The address of the token0 for pool
/// @return token1 The address of the token1 for pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function npmPositions(uint256 _tokenId)
external
view
override
nonZeroAddress(address(nonfungiblePositionManager))
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
return nonfungiblePositionManager.positions(_tokenId);
}
*/
/*
/// @dev snapshotCumulativesInside
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
/// @return curTimestamps current Timestamps
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
override
nonZeroAddress(poolAddress)
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside,
uint32 curTimestamps
)
{
tickCumulativeInside;
secondsPerLiquidityInsideX128;
secondsInside;
curTimestamps = uint32(block.timestamp);
(
tickCumulativeInside,
secondsPerLiquidityInsideX128,
secondsInside
) = IUniswapV3Pool(poolAddress).snapshotCumulativesInside(
tickLower,
tickUpper
);
}
*/
/// @dev mining end time
/// @return endTime mining end time
function miningEndTime()
external
view
override
nonZeroAddress(vault)
returns (uint256)
{
return IIStake2Vault(vault).miningEndTime();
}
/// @dev get price
/// @param decimals pool's token1's decimals (ex. 1e18)
/// @return price price
function getPrice(uint256 decimals)
external
view
override
nonZeroAddress(poolAddress)
returns (uint256 price)
{
(uint160 sqrtPriceX96, , , , , , ) =
IUniswapV3Pool(poolAddress).slot0();
return
uint256(sqrtPriceX96).mul(uint256(sqrtPriceX96)).mul(decimals) >>
(96 * 2);
}
/// @dev Liquidity provision time (seconds) at a specific point in time since the token was recently mined
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) set it to the current time.
/// @return secondsAbsolute Absolute duration (in seconds) from the latest mining to the time of expectTime
/// @return secondsInsideDiff256 The time (in seconds) that the token ID provided liquidity from the last claim (or staking time) to the present time.
/// @return expectTime time used in the calculation
function currentliquidityTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
public
view
override
nonZeroAddress(poolAddress)
returns (
uint256 secondsAbsolute,
uint256 secondsInsideDiff256,
uint256 expectTime
)
{
secondsAbsolute = 0;
secondsInsideDiff256 = 0;
expectTime = 0;
if (
stakeStartTime > 0 &&
expectBlocktimestamp > coinageLastMintBlockTimetamp
) {
expectTime = expectBlocktimestamp;
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
(, , uint160 secondsInside) =
IUniswapV3Pool(poolAddress).snapshotCumulativesInside(
_depositTokens.tickLower,
_depositTokens.tickUpper
);
if (
expectTime > _depositTokens.claimedTime &&
expectTime > _depositTokens.startTime
) {
if (_depositTokens.claimedTime > 0) {
secondsAbsolute = expectTime.sub(
(uint256)(_depositTokens.claimedTime)
);
} else {
secondsAbsolute = expectTime.sub(
(uint256)(_depositTokens.startTime)
);
}
if (secondsAbsolute > 0) {
if (_depositTokens.secondsInsideLast > 0) {
secondsInsideDiff256 = uint256(secondsInside).sub(
uint256(_depositTokens.secondsInsideLast)
);
} else {
secondsInsideDiff256 = uint256(secondsInside).sub(
uint256(_depositTokens.secondsInsideInitial)
);
}
}
}
}
}
/// @dev Coinage balance information that tokens can receive in the future
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return currentTotalCoinage Current Coinage Total Balance
/// @return afterTotalCoinage Total balance of Coinage at a future point in time
/// @return afterBalanceTokenId The total balance of the coin age of the token at a future time
/// @return expectTime future time
/// @return addIntervalTime Duration (in seconds) between the future time and the recent mining time
function currentCoinageBalanceTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
public
view
override
nonZeroAddress(poolAddress)
returns (
uint256 currentTotalCoinage,
uint256 afterTotalCoinage,
uint256 afterBalanceTokenId,
uint256 expectTime,
uint256 addIntervalTime
)
{
currentTotalCoinage = 0;
afterTotalCoinage = 0;
afterBalanceTokenId = 0;
expectTime = 0;
addIntervalTime = 0;
if (
stakeStartTime > 0 &&
expectBlocktimestamp > coinageLastMintBlockTimetamp
) {
expectTime = expectBlocktimestamp;
uint256 miningEndTime_ = IIStake2Vault(vault).miningEndTime();
if (expectTime > miningEndTime_) expectTime = miningEndTime_;
currentTotalCoinage = IAutoRefactorCoinageWithTokenId(coinage)
.totalSupply();
(uint256 balance, uint256 refactoredCount, uint256 remain) =
IAutoRefactorCoinageWithTokenId(coinage).balancesTokenId(
tokenId
);
uint256 coinageLastMintTime = coinageLastMintBlockTimetamp;
if (coinageLastMintTime == 0) coinageLastMintTime = stakeStartTime;
addIntervalTime = expectTime.sub(coinageLastMintTime);
if (
miningIntervalSeconds > 0 &&
addIntervalTime > miningIntervalSeconds
) addIntervalTime = addIntervalTime.sub(miningIntervalSeconds);
if (addIntervalTime > 0) {
uint256 miningPerSecond_ =
IIStake2Vault(vault).miningPerSecond();
uint256 addAmountCoinage =
addIntervalTime.mul(miningPerSecond_);
afterTotalCoinage = currentTotalCoinage.add(
addAmountCoinage.mul(10**9)
);
uint256 factor_ =
IAutoRefactorCoinageWithTokenId(coinage).factor();
uint256 infactor =
_calcNewFactor(
currentTotalCoinage,
afterTotalCoinage,
factor_
);
uint256 count = 0;
uint256 f = infactor;
for (; f >= 10**28; f = f.div(2)) {
count = count.add(1);
}
uint256 afterBalanceTokenId_ =
applyCoinageFactor(balance, refactoredCount, f, count);
afterBalanceTokenId = afterBalanceTokenId_.add(remain);
}
}
}
/// @dev Estimated additional claimable amount on a specific time
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return miningAmount Amount you can claim
/// @return nonMiningAmount The amount that burn without receiving a claim
/// @return minableAmount Total amount of mining allocated at the time of claim
/// @return minableAmountRay Total amount of mining allocated at the time of claim (ray unit)
/// @return expectTime time used in the calculation
function expectedPlusClaimableAmount(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
override
nonZeroAddress(poolAddress)
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint256 minableAmountRay,
uint256 expectTime
)
{
miningAmount = 0;
nonMiningAmount = 0;
minableAmount = 0;
minableAmountRay = 0;
expectTime = 0;
if (
stakeStartTime > 0 &&
expectBlocktimestamp > coinageLastMintBlockTimetamp
) {
expectTime = expectBlocktimestamp;
uint256 afterBalanceTokenId = 0;
uint256 secondsAbsolute = 0;
uint256 secondsInsideDiff256 = 0;
uint256 currentBalanceOfTokenId =
IAutoRefactorCoinageWithTokenId(coinage).balanceOf(tokenId);
(secondsAbsolute, secondsInsideDiff256, ) = currentliquidityTokenId(
tokenId,
expectTime
);
(, , afterBalanceTokenId, , ) = currentCoinageBalanceTokenId(
tokenId,
expectTime
);
if (
currentBalanceOfTokenId > 0 &&
afterBalanceTokenId > currentBalanceOfTokenId
) {
minableAmountRay = afterBalanceTokenId.sub(
currentBalanceOfTokenId
);
minableAmount = minableAmountRay.div(10**9);
}
if (minableAmount > 0 && secondsAbsolute > 0 && secondsInsideDiff256 > 0 ) {
if (
secondsInsideDiff256 < secondsAbsolute &&
secondsInsideDiff256 > 0
) {
miningAmount = minableAmount.mul(secondsInsideDiff256).div(
secondsAbsolute
);
nonMiningAmount = minableAmount.sub(miningAmount);
} else {
miningAmount = minableAmount;
}
} else if(secondsInsideDiff256 == 0){
nonMiningAmount = minableAmount;
}
}
}
function applyCoinageFactor(
uint256 v,
uint256 refactoredCount,
uint256 _factor,
uint256 refactorCount
) internal pure returns (uint256) {
if (v == 0) {
return 0;
}
v = rmul2(v, _factor);
for (uint256 i = refactoredCount; i < refactorCount; i++) {
v = v * (2);
}
return v;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
interface IStakeUniswapV3 {
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
/// @param deadline the deadline that valid the owner's signature
/// @param v the owner's signature - v
/// @param r the owner's signature - r
/// @param s the owner's signature - s
function stakePermit(
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
function stake(uint256 tokenId) external;
/// @dev view mining information of tokenId
/// @param tokenId tokenId
function getMiningTokenId(uint256 tokenId)
external
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint160 secondsInside,
uint256 secondsInsideDiff256,
uint256 liquidity,
uint256 balanceOfTokenIdRay,
uint256 minableAmountRay,
uint256 secondsInside256,
uint256 secondsAbsolute256
);
/// @dev withdraw the deposited token.
/// The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function withdraw(uint256 tokenId) external;
/// @dev The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function claim(uint256 tokenId) external;
// function setPool(
// address token0,
// address token1,
// string calldata defiInfoName
// ) external;
/// @dev
function getUserStakedTokenIds(address user)
external
view
returns (uint256[] memory ids);
/// @dev tokenId's deposited information
/// @param tokenId tokenId
/// @return poolAddress poolAddress
/// @return tick tick,
/// @return liquidity liquidity,
/// @return args liquidity, startTime, claimedTime, startBlock, claimedBlock, claimedAmount
/// @return secondsPL secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128Las
function getDepositToken(uint256 tokenId)
external
view
returns (
address poolAddress,
int24[2] memory tick,
uint128 liquidity,
uint256[5] memory args,
uint160[2] memory secondsPL
);
function getUserStakedTotal(address user)
external
view
returns (
uint256 totalDepositAmount,
uint256 totalClaimedAmount,
uint256 totalUnableClaimAmount
);
/// @dev Give the infomation of this stakeContracts
/// @return return1 [token, vault, stakeRegistry, coinage]
/// @return return2 [poolToken0, poolToken1, nonfungiblePositionManager, uniswapV3FactoryAddress]
/// @return return3 [totalStakers, totalStakedAmount, rewardClaimedTotal,rewardNonLiquidityClaimTotal]
function infos()
external
view
returns (
address[4] memory,
address[4] memory,
uint256[4] memory
);
/*
/// @dev pool's infos
/// @return factory pool's factory address
/// @return token0 token0 address
/// @return token1 token1 address
/// @return fee fee
/// @return tickSpacing tickSpacing
/// @return maxLiquidityPerTick maxLiquidityPerTick
/// @return liquidity pool's liquidity
function poolInfos()
external
view
returns (
address factory,
address token0,
address token1,
uint24 fee,
int24 tickSpacing,
uint128 maxLiquidityPerTick,
uint128 liquidity
);
/// @dev key's info
/// @param key hash(owner, tickLower, tickUpper)
/// @return _liquidity key's liquidity
/// @return feeGrowthInside0LastX128 key's feeGrowthInside0LastX128
/// @return feeGrowthInside1LastX128 key's feeGrowthInside1LastX128
/// @return tokensOwed0 key's tokensOwed0
/// @return tokensOwed1 key's tokensOwed1
function poolPositions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
*/
/// @dev pool's slot0 (current position)
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool
/// @return unlocked Whether the pool is currently locked to reentrancy
function poolSlot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/*
/// @dev _tokenId's position
/// @param _tokenId tokenId
/// @return nonce the nonce for permits
/// @return operator the address that is approved for spending this token
/// @return token0 The address of the token0 for pool
/// @return token1 The address of the token1 for pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function npmPositions(uint256 _tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @dev snapshotCumulativesInside
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
/// @return curTimestamps current Timestamps
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside,
uint32 curTimestamps
);
*/
/// @dev mining end time
/// @return endTime mining end time
function miningEndTime() external view returns (uint256 endTime);
/// @dev get price
/// @param decimals pool's token1's decimals (ex. 1e18)
/// @return price price
function getPrice(uint256 decimals) external view returns (uint256 price);
/// @dev Liquidity provision time (seconds) at a specific point in time since the token was recently mined
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) set it to the current time.
/// @return secondsAbsolute Absolute duration (in seconds) from the latest mining to the time of expectTime
/// @return secondsInsideDiff256 The time (in seconds) that the token ID provided liquidity from the last claim (or staking time) to the present time.
/// @return expectTime time used in the calculation
function currentliquidityTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
returns (
uint256 secondsAbsolute,
uint256 secondsInsideDiff256,
uint256 expectTime
);
/// @dev Coinage balance information that tokens can receive in the future
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return currentTotalCoinage Current Coinage Total Balance
/// @return afterTotalCoinage Total balance of Coinage at a future point in time
/// @return afterBalanceTokenId The total balance of the coin age of the token at a future time
/// @return expectTime future time
/// @return addIntervalTime Duration (in seconds) between the future time and the recent mining time
function currentCoinageBalanceTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
returns (
uint256 currentTotalCoinage,
uint256 afterTotalCoinage,
uint256 afterBalanceTokenId,
uint256 expectTime,
uint256 addIntervalTime
);
/// @dev Estimated additional claimable amount on a specific time
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return miningAmount Amount you can claim
/// @return nonMiningAmount The amount that burn without receiving a claim
/// @return minableAmount Total amount of mining allocated at the time of claim
/// @return minableAmountRay Total amount of mining allocated at the time of claim (ray unit)
/// @return expectTime time used in the calculation
function expectedPlusClaimableAmount(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint256 minableAmountRay,
uint256 expectTime
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IAutoRefactorCoinageWithTokenId {
function factor() external view returns (uint256);
function _factor() external view returns (uint256);
function refactorCount() external view returns (uint256);
function balancesTokenId(uint256 tokenId)
external
view
returns (
uint256 balance,
uint256 refactoredCount,
uint256 remain
);
function setFactor(uint256 factor_) external returns (uint256);
function burn(
address tokenOwner,
uint256 tokenId,
uint256 amount
) external;
function mint(
address tokenOwner,
uint256 tokenId,
uint256 amount
) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(uint256 tokenId) external view returns (uint256);
function burnTokenId(address tokenOwner, uint256 tokenId) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
//pragma abicoder v2;
//import "../libraries/LibTokenStake1.sol";
interface IIStake2Vault {
/// @dev of according to request from(staking contract) the amount of mining is paid to to.
/// @param to the address that will receive the reward
/// @param minableAmount minable amount
/// @param miningAmount amount mined
/// @param nonMiningAmount Amount not mined
function claimMining(
address to,
uint256 minableAmount,
uint256 miningAmount,
uint256 nonMiningAmount
) external returns (bool);
/// @dev mining per second
function miningPerSecond() external view returns (uint256);
/// @dev mining start time
function miningStartTime() external view returns (uint256);
/// @dev mining end time
function miningEndTime() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// https://github.com/dapphub/ds-math/blob/de45767/src/math.sol
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >0.4.13;
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
function wmul2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, y) / WAD;
}
function rmul2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, y) / RAY;
}
function wdiv2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, WAD) / y;
}
function rdiv2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, RAY) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function wpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : WAD;
for (n /= 2; n != 0; n /= 2) {
x = wmul(x, x);
if (n % 2 != 0) {
z = wmul(z, x);
}
}
}
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./AccessRoleCommon.sol";
contract AccessibleCommon is AccessRoleCommon, AccessControl {
modifier onlyOwner() {
require(isAdmin(msg.sender), "Accessible: Caller is not an admin");
_;
}
/// @dev add admin
/// @param account address to add
function addAdmin(address account) public virtual onlyOwner {
grantRole(ADMIN_ROLE, account);
}
/// @dev remove admin
/// @param account address to remove
function removeAdmin(address account) public virtual onlyOwner {
renounceRole(ADMIN_ROLE, account);
}
/// @dev transfer admin
/// @param newAdmin new admin address
function transferAdmin(address newAdmin) external virtual onlyOwner {
require(newAdmin != address(0), "Accessible: zero address");
require(msg.sender != newAdmin, "Accessible: same admin");
grantRole(ADMIN_ROLE, newAdmin);
renounceRole(ADMIN_ROLE, msg.sender);
}
/// @dev whether admin
/// @param account address to check
function isAdmin(address account) public view virtual returns (bool) {
return hasRole(ADMIN_ROLE, account);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
import "../libraries/LibUniswapV3Stake.sol";
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
/// @title The base storage of stakeContract
contract StakeUniswapV3Storage {
/// @dev reward token : TOS
address public token;
/// @dev registry
address public stakeRegistry;
/// @dev A vault that holds tos rewards.
address public vault;
/// @dev the total minied amount
uint256 public miningAmountTotal;
/// @dev Rewards have been allocated,
/// but liquidity is lost, and burned amount .
uint256 public nonMiningAmountTotal;
/// @dev the total staked amount
uint256 public totalStakedAmount;
/// @dev user's tokenIds
mapping(address => uint256[]) public userStakedTokenIds;
/// @dev Deposited token ID information
mapping(uint256 => LibUniswapV3Stake.StakeLiquidity) public depositTokens;
/// @dev Amount that Token ID put into Coinage
mapping(uint256 => LibUniswapV3Stake.StakedTokenAmount)
public stakedCoinageTokens;
/// @dev Total staked information of users
mapping(address => LibUniswapV3Stake.StakedTotalTokenAmount)
public userTotalStaked;
/// @dev total stakers
uint256 public totalStakers;
/// @dev lock
uint256 internal _lock;
/// @dev flag for pause proxy
bool public pauseProxy;
/// @dev stakeStartTime is set when staking for the first time
uint256 public stakeStartTime;
/// @dev saleStartTime
uint256 public saleStartTime;
/// @dev Mining interval can be given to save gas cost.
uint256 public miningIntervalSeconds;
/// @dev pools's token
address public poolToken0;
address public poolToken1;
address public poolAddress;
uint256 public poolFee;
/// @dev Rewards per second liquidity inside (3년간 8000000 TOS)
/// uint256 internal MINING_PER_SECOND = 84559445290038900;
/// @dev UniswapV3 Nonfungible position manager
INonfungiblePositionManager public nonfungiblePositionManager;
/// @dev UniswapV3 pool factory
address public uniswapV3FactoryAddress;
/// @dev coinage for reward 리워드 계산을 위한 코인에이지
address public coinage;
/// @dev recently mined time (in seconds)
uint256 public coinageLastMintBlockTimetamp;
/// @dev total tokenIds
uint256 public totalTokens;
///@dev for migrate L2
bool public migratedL2;
modifier nonZeroAddress(address _addr) {
require(_addr != address(0), "StakeUniswapV3Storage: zero address");
_;
}
modifier lock() {
require(_lock == 0, "StakeUniswapV3Storage: LOCKED");
_lock = 1;
_;
_lock = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @title SafeMath32
* @dev SafeMath library implemented for uint32
*/
library SafeMath32 {
function mul(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint32 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract AccessRoleCommon {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant BURNER_ROLE = keccak256("BURNER");
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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: Unlicense
pragma solidity ^0.7.6;
library LibUniswapV3Stake {
struct StakeLiquidity {
address owner;
uint256 idIndex;
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
uint32 startTime;
uint32 claimedTime;
uint160 secondsInsideInitial;
uint160 secondsInsideLast;
bool claimLock;
bool withdraw;
}
struct StakedTokenAmount {
uint256 amount;
uint32 startTime;
uint32 claimedTime;
uint256 claimedAmount;
uint256 nonMiningAmount;
}
struct StakedTotalTokenAmount {
bool staked;
uint256 totalDepositAmount;
uint256 totalMiningAmount;
uint256 totalNonMiningAmount;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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.6.2 <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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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);
}
|
get price decimals pool's token1's decimals (ex. 1e18) return price price
|
function getPrice(uint256 decimals)
external
view
override
nonZeroAddress(poolAddress)
returns (uint256 price)
{
(uint160 sqrtPriceX96, , , , , , ) =
IUniswapV3Pool(poolAddress).slot0();
return
uint256(sqrtPriceX96).mul(uint256(sqrtPriceX96)).mul(decimals) >>
(96 * 2);
}
| 12,109,808 |
//SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
/// @title Unipilot Yield Farming
/// @author Asim Raza
/// @notice You can use this contract for earn reward on staking nft
/// @dev All function calls are currently implemented without side effects
//Utility imports
import "./interfaces/IUnipilotFarm.sol";
import "./interfaces/uniswap/IUniswapLiquidityManager.sol";
import "./interfaces/IUnipilot.sol";
import "./interfaces/IFarmV1.sol";
import "./interfaces/IUnipilotStake.sol";
//Uniswap v3 core imports
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
//Openzeppelin imports
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./ReentrancyGuard.sol";
contract UnipilotFarm is IUnipilotFarm, ReentrancyGuard, IERC721Receiver {
using SafeMath for uint256;
using SafeERC20 for IERC20;
bool public isFarmingActive;
bool public backwardCompatible;
address public governance;
uint256 public pilotPerBlock = 1e18;
uint256 public farmingGrowthBlockLimit;
uint256 public totalRewardSent;
address private ulm;
address private stakeContract;
address[2] private deprecated;
address private constant PILOT_TOKEN = 0x37C997B35C619C21323F3518B9357914E8B99525;
address private constant UNIPILOT = 0xde5bF92E3372AA59C73Ca7dFc6CEc599E1B2b08C;
address[] public poolListed;
// farming status --> tokenId => bool
mapping(uint256 => bool) public farmingActive;
// exist in whitelist or not --> pool address => bool
mapping(address => bool) public poolWhitelist;
// poolinfo address =>Poolinfo struct
mapping(address => PoolInfo) public poolInfo;
// poolAltInfo address => PoolAltInfo struct
mapping(address => PoolAltInfo) public poolAltInfo;
// userinfo user --> tokenId nft => userInfo struct
mapping(uint256 => UserInfo) public userInfo;
//user address => pool address => tokenId[]
mapping(address => mapping(address => uint256[])) public userToPoolToTokenIds;
modifier onlyGovernance() {
require(msg.sender == governance, "NA");
_;
}
modifier isActive() {
require(isFarmingActive, "FNA");
_;
}
modifier isLimitActive() {
require(farmingGrowthBlockLimit == 0, "LA");
_;
}
modifier onlyOwner(uint256 _tokenId) {
require(IERC721(UNIPILOT).ownerOf(_tokenId) == msg.sender, "NO");
_;
}
modifier isPoolRewardActive(address pool) {
require(poolInfo[pool].isRewardActive, "RNA");
_;
}
modifier onlyStake() {
require(msg.sender == stakeContract, "NS");
_;
}
constructor(
address _ulm,
address _governance,
address[2] memory _deprecated
) {
governance = _governance;
ulm = _ulm;
isFarmingActive = true;
deprecated = _deprecated;
backwardCompatible = true;
}
/// @notice withdraw NFT with reward
/// @dev only owner of nft can withdraw
/// @param _tokenId unstake tokenID
function withdrawNFT(uint256 _tokenId) external override {
UserInfo storage userState = userInfo[_tokenId];
PoolInfo storage poolState = poolInfo[userState.pool];
PoolAltInfo storage poolAltState = poolAltInfo[userState.pool];
withdrawReward(_tokenId);
poolState.totalLockedLiquidity = poolState.totalLockedLiquidity.sub(
userState.liquidity
);
IERC721(UNIPILOT).safeTransferFrom(address(this), msg.sender, _tokenId);
farmingActive[_tokenId] = false;
emit WithdrawNFT(
userState.pool,
userState.user,
_tokenId,
poolState.totalLockedLiquidity
);
if (poolState.totalLockedLiquidity == 0) {
poolState.startBlock = block.number;
poolState.lastRewardBlock = block.number;
poolState.globalReward = 0;
poolAltState.startBlock = block.number;
poolAltState.lastRewardBlock = block.number;
poolAltState.globalReward = 0;
}
uint256 index = callIndex(userState.pool, _tokenId);
updateNFTList(index, userState.user, userState.pool);
delete userInfo[_tokenId];
}
/// @notice withdraw NFT without reward claiming
/// @param _tokenId unstake this tokenID
function emergencyNFTWithdraw(uint256 _tokenId) external {
UserInfo storage userState = userInfo[_tokenId];
require(userState.user == msg.sender, "NOO");
PoolInfo storage poolState = poolInfo[userState.pool];
PoolAltInfo storage poolAltState = poolAltInfo[userState.pool];
poolState.totalLockedLiquidity = poolState.totalLockedLiquidity.sub(
userState.liquidity
);
IERC721(UNIPILOT).safeTransferFrom(address(this), userState.user, _tokenId);
if (poolState.totalLockedLiquidity == 0) {
poolState.startBlock = block.number;
poolState.lastRewardBlock = block.number;
poolState.globalReward = 0;
poolAltState.startBlock = block.number;
poolAltState.lastRewardBlock = block.number;
poolAltState.globalReward = 0;
}
uint256 index = callIndex(userState.pool, _tokenId);
updateNFTList(index, userState.user, userState.pool);
delete userInfo[_tokenId];
}
/// @notice Migrate funds to Governance address or in new Contract
/// @dev only governance can call this
/// @param _newContract address of new contract or wallet address
/// @param _tokenAddress address of token which want to migrate
/// @param _amount withdraw that amount which are required
function migrateFunds(
address _newContract,
address _tokenAddress,
uint256 _amount
) external onlyGovernance {
require(_newContract != address(0), "CNE");
IERC20(_tokenAddress).safeTransfer(_newContract, _amount);
emit MigrateFunds(_newContract, _tokenAddress, _amount);
}
/// @notice Use to blacklist pools
/// @dev only governance can call this
/// @param _pools addresses to be blacklisted
function blacklistPools(address[] memory _pools) external override onlyGovernance {
for (uint256 i = 0; i < _pools.length; i++) {
poolWhitelist[_pools[i]] = false;
poolInfo[_pools[i]].rewardMultiplier = 0;
emit BlacklistPool(_pools[i], poolWhitelist[_pools[i]], block.timestamp);
}
}
/// @notice Use to update ULM address
/// @dev only governance can call this
/// @param _ulm new address of ULM
function updateULM(address _ulm) external override onlyGovernance {
emit UpdateULM(ulm, ulm = _ulm, block.timestamp);
}
/// @notice Updating pilot per block for every pool
/// @dev only governance can call this
/// @param _value new value of pilot per block
function updatePilotPerBlock(uint256 _value) external override onlyGovernance {
address[] memory pools = poolListed;
pilotPerBlock = _value;
for (uint256 i = 0; i < pools.length; i++) {
if (poolWhitelist[pools[i]]) {
if (poolInfo[pools[i]].totalLockedLiquidity != 0) {
updatePoolState(pools[i]);
}
emit UpdatePilotPerBlock(pools[i], pilotPerBlock);
}
}
}
/// @notice Updating multiplier for single pool
/// @dev only governance can call this
/// @param _pool pool address
/// @param _value new value of multiplier of pool
function updateMultiplier(address _pool, uint256 _value)
external
override
onlyGovernance
{
updatePoolState(_pool);
emit UpdateMultiplier(
_pool,
poolInfo[_pool].rewardMultiplier,
poolInfo[_pool].rewardMultiplier = _value
);
}
/// @notice User total nft(s) with respect to pool
/// @param _user particular user address
/// @param _pool particular pool address
/// @return tokenCount count of nft(s)
/// @return tokenIds array of tokenID
function totalUserNftWRTPool(address _user, address _pool)
external
view
override
returns (uint256 tokenCount, uint256[] memory tokenIds)
{
tokenCount = userToPoolToTokenIds[_user][_pool].length;
tokenIds = userToPoolToTokenIds[_user][_pool];
}
/// @notice NFT token ID farming status
/// @param _tokenId particular tokenId
function nftStatus(uint256 _tokenId) external view override returns (bool) {
return farmingActive[_tokenId];
}
/// @notice User can call tx to deposit nft
/// @dev pool address must be exist in whitelisted pools
/// @param _tokenId tokenID which want to deposit
/// @return status of farming is active for particular tokenID
function depositNFT(uint256 _tokenId)
external
override
isActive
isLimitActive
onlyOwner(_tokenId)
returns (bool)
{
address sender = msg.sender;
IUniswapLiquidityManager.Position memory positions = IUniswapLiquidityManager(ulm)
.userPositions(_tokenId);
(address pool, uint256 liquidity) = (positions.pool, positions.liquidity);
require(poolWhitelist[pool], "PNW");
IUniswapLiquidityManager.LiquidityPosition
memory liquidityPositions = IUniswapLiquidityManager(ulm).poolPositions(pool);
uint256 totalLiquidity = liquidityPositions.totalLiquidity;
require(totalLiquidity >= liquidity && liquidity > 0, "IL");
PoolInfo storage poolState = poolInfo[pool];
if (poolState.lastRewardBlock != poolState.startBlock) {
uint256 blockDifference = (block.number).sub(poolState.lastRewardBlock);
poolState.globalReward = getGlobalReward(
pool,
blockDifference,
pilotPerBlock,
poolState.rewardMultiplier,
poolState.globalReward
);
}
poolState.totalLockedLiquidity = poolState.totalLockedLiquidity.add(liquidity);
userInfo[_tokenId] = UserInfo({
pool: pool,
liquidity: liquidity,
user: sender,
reward: poolState.globalReward,
altReward: userInfo[_tokenId].altReward,
boosterActive: false
});
userToPoolToTokenIds[sender][pool].push(_tokenId);
farmingActive[_tokenId] = true; // user's farming active
IERC721(UNIPILOT).safeTransferFrom(sender, address(this), _tokenId);
if (poolState.isAltActive) {
altGR(pool, _tokenId);
}
poolState.lastRewardBlock = block.number;
emit Deposit(
pool,
_tokenId,
userInfo[_tokenId].liquidity,
poolState.totalLockedLiquidity,
poolState.globalReward,
poolState.rewardMultiplier,
pilotPerBlock
);
return farmingActive[_tokenId];
}
/// @notice toggle alt token state on pool
/// @dev only governance can call this
/// @param _pool pool address for alt token
function toggleActiveAlt(address _pool) external onlyGovernance returns (bool) {
require(poolAltInfo[_pool].altToken != address(0), "TNE");
emit UpdateAltState(
poolInfo[_pool].isAltActive,
poolInfo[_pool].isAltActive = !poolInfo[_pool].isAltActive,
_pool
);
if (poolInfo[_pool].isAltActive) {
updateAltPoolState(_pool);
} else {
poolAltInfo[_pool].lastRewardBlock = block.number;
}
return poolInfo[_pool].isAltActive;
}
///@notice Updating address of alt token
///@dev only Governance can call this
function updateAltToken(address _pool, address _altToken) external onlyGovernance {
emit UpdateActiveAlt(
poolAltInfo[_pool].altToken,
poolAltInfo[_pool].altToken = _altToken,
_pool
);
PoolAltInfo memory poolAltState = poolAltInfo[_pool];
poolAltState = PoolAltInfo({
globalReward: 0,
lastRewardBlock: block.number,
altToken: poolAltInfo[_pool].altToken,
startBlock: block.number
});
poolAltInfo[_pool] = poolAltState;
}
/// @dev onlyGovernance can call this
/// @param _pools The pools to make whitelist or initialize
/// @param _multipliers multiplier of pools
function initializer(address[] memory _pools, uint256[] memory _multipliers)
public
override
onlyGovernance
{
require(_pools.length == _multipliers.length, "LNS");
for (uint256 i = 0; i < _pools.length; i++) {
if (
!poolWhitelist[_pools[i]] && poolInfo[_pools[i]].startBlock == 0
) {
insertPool(_pools[i], _multipliers[i]);
} else {
poolWhitelist[_pools[i]] = true;
poolInfo[_pools[i]].rewardMultiplier = _multipliers[i];
}
}
}
/// @notice Generic function to calculating global reward
/// @param pool pool address
/// @param blockDifference difference of block from current block to last reward block
/// @param rewardPerBlock reward on per block
/// @param multiplier multiplier value
/// @return globalReward calculating global reward
function getGlobalReward(
address pool,
uint256 blockDifference,
uint256 rewardPerBlock,
uint256 multiplier,
uint256 _globalReward
) public view returns (uint256 globalReward) {
uint256 tvl;
if (backwardCompatible) {
for(uint i = 0; i < deprecated.length; i++){
uint256 prevTvl=(IUnipilotFarmV1(deprecated[i]).poolInfo(pool).totalLockedLiquidity);
tvl=tvl.add(prevTvl);
}
tvl = tvl.add(poolInfo[pool].totalLockedLiquidity);
} else {
tvl = poolInfo[pool].totalLockedLiquidity;
}
uint256 temp = FullMath.mulDiv(rewardPerBlock, multiplier, 1e18);
globalReward = FullMath.mulDiv(blockDifference.mul(temp), 1e18, tvl).add(
_globalReward
);
}
/// @notice Generic function to calculating reward of tokenId
/// @param _tokenId find current reward of tokenID
/// @return pilotReward calculate pilot reward
/// @return globalReward calculate global reward
/// @return globalAltReward calculate global reward of alt token
/// @return altReward calculate reward of alt token
function currentReward(uint256 _tokenId)
public
view
override
returns (
uint256 pilotReward,
uint256 globalReward,
uint256 globalAltReward,
uint256 altReward
)
{
UserInfo memory userState = userInfo[_tokenId];
PoolInfo memory poolState = poolInfo[userState.pool];
PoolAltInfo memory poolAltState = poolAltInfo[userState.pool];
DirectTo check = DirectTo.GRforPilot;
if (isFarmingActive) {
globalReward = checkLimit(_tokenId, check);
if (poolState.isAltActive) {
check = DirectTo.GRforAlt;
globalAltReward = checkLimit(_tokenId, check);
} else {
globalAltReward = poolAltState.globalReward;
}
} else {
globalReward = poolState.globalReward;
globalAltReward = poolAltState.globalReward;
}
uint256 userReward = globalReward.sub(userState.reward);
uint256 _reward = (userReward.mul(userState.liquidity)).div(1e18);
if (userState.boosterActive) {
uint256 multiplier = IUnipilotStake(stakeContract).getBoostMultiplier(
userState.user,
userState.pool,
_tokenId
);
uint256 boostedReward = (_reward.mul(multiplier)).div(1e18);
pilotReward = _reward.add((boostedReward));
} else {
pilotReward = _reward;
}
_reward = globalAltReward.sub(userState.altReward);
altReward = (_reward.mul(userState.liquidity)).div(1e18);
}
/// @notice Generic function to check limit of global reward of token Id
function checkLimit(uint256 _tokenId, DirectTo _check)
internal
view
returns (uint256 globalReward)
{
address pool = userInfo[_tokenId].pool;
TempInfo memory poolState;
if (_check == DirectTo.GRforPilot) {
poolState = TempInfo({
globalReward: poolInfo[pool].globalReward,
lastRewardBlock: poolInfo[pool].lastRewardBlock,
rewardMultiplier: poolInfo[pool].rewardMultiplier
});
} else if (_check == DirectTo.GRforAlt) {
poolState = TempInfo({
globalReward: poolAltInfo[pool].globalReward,
lastRewardBlock: poolAltInfo[pool].lastRewardBlock,
rewardMultiplier: poolInfo[pool].rewardMultiplier
});
}
if (
poolState.lastRewardBlock < farmingGrowthBlockLimit &&
block.number > farmingGrowthBlockLimit
) {
globalReward = getGlobalReward(
pool,
farmingGrowthBlockLimit.sub(poolState.lastRewardBlock),
pilotPerBlock,
poolState.rewardMultiplier,
poolState.globalReward
);
} else if (
poolState.lastRewardBlock > farmingGrowthBlockLimit &&
farmingGrowthBlockLimit > 0
) {
globalReward = poolState.globalReward;
} else {
uint256 blockDifference = (block.number).sub(poolState.lastRewardBlock);
globalReward = getGlobalReward(
pool,
blockDifference,
pilotPerBlock,
poolState.rewardMultiplier,
poolState.globalReward
);
}
}
/// @notice Withdraw reward of token Id
/// @dev only owner of nft can withdraw
/// @param _tokenId withdraw reward of this tokenID
function withdrawReward(uint256 _tokenId)
public
override
nonReentrant
isPoolRewardActive(userInfo[_tokenId].pool)
{
UserInfo storage userState = userInfo[_tokenId];
PoolInfo storage poolState = poolInfo[userState.pool];
require(userState.user == msg.sender, "NO");
(
uint256 pilotReward,
uint256 globalReward,
uint256 globalAltReward,
uint256 altReward
) = currentReward(_tokenId);
require(IERC20(PILOT_TOKEN).balanceOf(address(this)) >= pilotReward, "IF");
poolState.globalReward = globalReward;
poolState.lastRewardBlock = block.number;
userState.reward = globalReward;
totalRewardSent += pilotReward;
IERC20(PILOT_TOKEN).safeTransfer(userInfo[_tokenId].user, pilotReward);
if (poolState.isAltActive) {
altWithdraw(_tokenId, globalAltReward, altReward);
}
emit WithdrawReward(
userState.pool,
_tokenId,
userState.liquidity,
userState.reward,
poolState.globalReward,
poolState.totalLockedLiquidity,
pilotReward
);
}
/// @notice internal function use for initialize struct values of single pool
/// @dev generalFunction to add pools
/// @param _pool pool address
function insertPool(address _pool, uint256 _multiplier) internal {
poolWhitelist[_pool] = true;
poolListed.push(_pool);
poolInfo[_pool] = PoolInfo({
startBlock: block.number,
globalReward: 0,
lastRewardBlock: block.number,
totalLockedLiquidity: 0,
rewardMultiplier: _multiplier,
isRewardActive: true,
isAltActive: poolInfo[_pool].isAltActive
});
emit NewPool(
_pool,
pilotPerBlock,
poolInfo[_pool].rewardMultiplier,
poolInfo[_pool].lastRewardBlock,
poolWhitelist[_pool]
);
}
/// @notice Use to update state of alt token
function altGR(address _pool, uint256 _tokenId) internal {
PoolAltInfo storage poolAltState = poolAltInfo[_pool];
if (poolAltState.lastRewardBlock != poolAltState.startBlock) {
uint256 blockDifference = (block.number).sub(poolAltState.lastRewardBlock);
poolAltState.globalReward = getGlobalReward(
_pool,
blockDifference,
pilotPerBlock,
poolInfo[_pool].rewardMultiplier,
poolAltState.globalReward
);
}
poolAltState.lastRewardBlock = block.number;
userInfo[_tokenId].altReward = poolAltState.globalReward;
}
/// @notice Use for pool tokenId to find its index
function callIndex(address pool, uint256 _tokenId)
internal
view
returns (uint256 index)
{
uint256[] memory tokens = userToPoolToTokenIds[msg.sender][pool];
for (uint256 i = 0; i <= tokens.length; i++) {
if (_tokenId == userToPoolToTokenIds[msg.sender][pool][i]) {
index = i;
break;
}
}
return index;
}
/// @notice Use to update list of NFT(s)
function updateNFTList(
uint256 _index,
address user,
address pool
) internal {
require(_index < userToPoolToTokenIds[user][pool].length, "IOB");
uint256 temp = userToPoolToTokenIds[user][pool][
userToPoolToTokenIds[user][pool].length.sub(1)
];
userToPoolToTokenIds[user][pool][_index] = temp;
userToPoolToTokenIds[user][pool].pop();
}
/// @notice Use to toggle farming state of contract
function toggleFarmingActive() external override onlyGovernance {
emit FarmingStatus(
isFarmingActive,
isFarmingActive = !isFarmingActive,
block.timestamp
);
}
/// @notice Use to withdraw alt tokens of token Id (internal)
function altWithdraw(
uint256 _tokenId,
uint256 altGlobalReward,
uint256 altReward
) internal {
PoolAltInfo storage poolAltState = poolAltInfo[userInfo[_tokenId].pool];
require(
IERC20(poolAltState.altToken).balanceOf(address(this)) >= altReward,
"IF"
);
poolAltState.lastRewardBlock = block.number;
poolAltState.globalReward = altGlobalReward;
userInfo[_tokenId].altReward = altGlobalReward;
IERC20(poolAltState.altToken).safeTransfer(userInfo[_tokenId].user, altReward);
}
/// @notice Use to toggle state of reward of pool
function toggleRewardStatus(address _pool) external override onlyGovernance {
if (poolInfo[_pool].isRewardActive) {
updatePoolState(_pool);
} else {
poolInfo[_pool].lastRewardBlock = block.number;
}
emit RewardStatus(
_pool,
poolInfo[_pool].isRewardActive,
poolInfo[_pool].isRewardActive = !poolInfo[_pool].isRewardActive
);
}
/// @notice Use to update pool state (internal)
function updatePoolState(address _pool) internal {
PoolInfo storage poolState = poolInfo[_pool];
if (poolState.totalLockedLiquidity > 0) {
uint256 currentGlobalReward = getGlobalReward(
_pool,
(block.number).sub(poolState.lastRewardBlock),
pilotPerBlock,
poolState.rewardMultiplier,
poolState.globalReward
);
poolState.globalReward = currentGlobalReward;
poolState.lastRewardBlock = block.number;
}
}
/// @notice Use to update alt token state (internal)
function updateAltPoolState(address _pool) internal {
PoolAltInfo storage poolAltState = poolAltInfo[_pool];
if (poolInfo[_pool].totalLockedLiquidity > 0) {
uint256 currentGlobalReward = getGlobalReward(
_pool,
(block.number).sub(poolAltState.lastRewardBlock),
pilotPerBlock,
poolInfo[_pool].rewardMultiplier,
poolAltState.globalReward
);
poolAltState.globalReward = currentGlobalReward;
poolAltState.lastRewardBlock = block.number;
}
}
/// @notice Use to stop staking NFT(s) in contract after block limit
function updateFarmingLimit(uint256 _blockNumber) external onlyGovernance {
emit UpdateFarmingLimit(
farmingGrowthBlockLimit,
farmingGrowthBlockLimit = _blockNumber
);
}
/// @notice toggle booster status of token Id
function toggleBooster(uint256 tokenId) external onlyStake {
emit ToggleBooster(
tokenId,
userInfo[tokenId].boosterActive,
userInfo[tokenId].boosterActive = !userInfo[tokenId].boosterActive
);
}
/// @notice set stake contract address
function setStake(address _stakeContract) external onlyGovernance {
emit Stake(stakeContract, stakeContract = _stakeContract);
}
/// @notice toggle backward compayibility status of FarmingV1
function toggleBackwardCompatibility() external onlyGovernance {
emit BackwardCompatible(
backwardCompatible,
backwardCompatible = !backwardCompatible
);
}
/// @notice governance can update new address of governance
function updateGovernance(address _governance) external onlyGovernance {
emit GovernanceUpdated(governance, governance = _governance);
}
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
receive() external payable {
//payable
}
}
//SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;
interface IUnipilotFarm {
struct PoolInfo {
uint256 startBlock;
uint256 globalReward;
uint256 lastRewardBlock;
uint256 totalLockedLiquidity;
uint256 rewardMultiplier;
bool isRewardActive;
bool isAltActive;
}
struct PoolAltInfo {
address altToken;
uint256 startBlock;
uint256 globalReward;
uint256 lastRewardBlock;
}
struct UserInfo {
bool boosterActive;
address pool;
address user;
uint256 reward;
uint256 altReward;
uint256 liquidity;
}
struct TempInfo {
uint256 globalReward;
uint256 lastRewardBlock;
uint256 rewardMultiplier;
}
enum DirectTo {
GRforPilot,
GRforAlt
}
event Deposit(
address pool,
uint256 tokenId,
uint256 liquidity,
uint256 totalSupply,
uint256 globalReward,
uint256 rewardMultiplier,
uint256 rewardPerBlock
);
event WithdrawReward(
address pool,
uint256 tokenId,
uint256 liquidity,
uint256 reward,
uint256 globalReward,
uint256 totalSupply,
uint256 lastRewardTransferred
);
event WithdrawNFT(
address pool,
address userAddress,
uint256 tokenId,
uint256 totalSupply
);
event NewPool(
address pool,
uint256 rewardPerBlock,
uint256 rewardMultiplier,
uint256 lastRewardBlock,
bool status
);
event BlacklistPool(address pool, bool status, uint256 time);
event UpdateULM(address oldAddress, address newAddress, uint256 time);
event UpdatePilotPerBlock(address pool, uint256 updated);
event UpdateMultiplier(address pool, uint256 old, uint256 updated);
event UpdateActiveAlt(address old, address updated, address pool);
event UpdateAltState(bool old, bool updated, address pool);
event UpdateFarmingLimit(uint256 old, uint256 updated);
event RewardStatus(address pool, bool old, bool updated);
event MigrateFunds(address account, address token, uint256 amount);
event FarmingStatus(bool old, bool updated, uint256 time);
event Stake(address old, address updated);
event ToggleBooster(uint256 tokenId, bool old, bool updated);
event UserBooster(uint256 tokenId, uint256 booster);
event BackwardCompatible(bool old, bool updated);
event GovernanceUpdated(address old, address updated);
function initializer(address[] memory pools, uint256[] memory _multipliers) external;
function blacklistPools(address[] memory pools) external;
function updatePilotPerBlock(uint256 value) external;
function updateMultiplier(address pool, uint256 value) external;
function updateULM(address _ULM) external;
function totalUserNftWRTPool(address userAddress, address pool)
external
view
returns (uint256 tokenCount, uint256[] memory tokenIds);
function nftStatus(uint256 tokenId) external view returns (bool);
function depositNFT(uint256 tokenId) external returns (bool);
function withdrawNFT(uint256 tokenId) external;
function withdrawReward(uint256 tokenId) external;
function currentReward(uint256 _tokenId)
external
view
returns (
uint256 pilotReward,
uint256 globalReward,
uint256 globalAltReward,
uint256 altReward
);
function toggleRewardStatus(address pool) external;
function toggleFarmingActive() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "./IULMEvents.sol";
interface IUniswapLiquidityManager is IULMEvents {
struct LiquidityPosition {
// base order position
int24 baseTickLower;
int24 baseTickUpper;
uint128 baseLiquidity;
// range order position
int24 rangeTickLower;
int24 rangeTickUpper;
uint128 rangeLiquidity;
// accumulated fees
uint256 fees0;
uint256 fees1;
uint256 feeGrowthGlobal0;
uint256 feeGrowthGlobal1;
// total liquidity
uint256 totalLiquidity;
// pool premiums
bool feesInPilot;
// oracle address for tokens to fetch prices from
address oracle0;
address oracle1;
// rebase
uint256 timestamp;
uint8 counter;
bool status;
bool managed;
}
struct Position {
uint256 nonce;
address pool;
uint256 liquidity;
uint256 feeGrowth0;
uint256 feeGrowth1;
uint256 tokensOwed0;
uint256 tokensOwed1;
}
struct ReadjustVars {
bool zeroForOne;
address poolAddress;
int24 currentTick;
uint160 sqrtPriceX96;
uint160 exactSqrtPriceImpact;
uint160 sqrtPriceLimitX96;
uint128 baseLiquidity;
uint256 amount0;
uint256 amount1;
uint256 amountIn;
uint256 amount0Added;
uint256 amount1Added;
uint256 amount0Range;
uint256 amount1Range;
uint256 currentTimestamp;
uint256 gasUsed;
uint256 pilotAmount;
}
struct VarsEmerency {
address token;
address pool;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
}
struct WithdrawVars {
address recipient;
uint256 amount0Removed;
uint256 amount1Removed;
uint256 userAmount0;
uint256 userAmount1;
uint256 pilotAmount;
}
struct WithdrawTokenOwedParams {
address token0;
address token1;
uint256 tokensOwed0;
uint256 tokensOwed1;
}
struct MintCallbackData {
address payer;
address token0;
address token1;
uint24 fee;
}
struct UnipilotProtocolDetails {
uint8 swapPercentage;
uint24 swapPriceThreshold;
uint256 premium;
uint256 gasPriceLimit;
uint256 userPilotPercentage;
uint256 feesPercentageIndexFund;
uint24 readjustFrequencyTime;
uint16 poolCardinalityDesired;
address pilotWethPair;
address oracle;
address indexFund; // 10%
address uniStrategy;
address unipilot;
}
struct SwapCallbackData {
address token0;
address token1;
uint24 fee;
}
struct AddLiquidityParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
}
struct RemoveLiquidity {
uint256 amount0;
uint256 amount1;
uint128 liquidityRemoved;
uint256 feesCollected0;
uint256 feesCollected1;
}
struct Tick {
int24 baseTickLower;
int24 baseTickUpper;
int24 bidTickLower;
int24 bidTickUpper;
int24 rangeTickLower;
int24 rangeTickUpper;
}
struct TokenDetails {
address token0;
address token1;
uint24 fee;
int24 currentTick;
uint16 poolCardinality;
uint128 baseLiquidity;
uint128 bidLiquidity;
uint128 rangeLiquidity;
uint256 amount0Added;
uint256 amount1Added;
}
struct DistributeFeesParams {
bool pilotToken;
bool wethToken;
address pool;
address recipient;
uint256 tokenId;
uint256 liquidity;
uint256 amount0Removed;
uint256 amount1Removed;
}
struct AddLiquidityManagerParams {
address pool;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 shares;
}
struct DepositVars {
uint24 fee;
address pool;
uint256 amount0Base;
uint256 amount1Base;
uint256 amount0Range;
uint256 amount1Range;
}
struct RangeLiquidityVars {
address token0;
address token1;
uint24 fee;
uint128 rangeLiquidity;
uint256 amount0Range;
uint256 amount1Range;
}
struct IncreaseParams {
address token0;
address token1;
uint24 fee;
int24 currentTick;
uint128 baseLiquidity;
uint256 baseAmount0;
uint256 baseAmount1;
uint128 rangeLiquidity;
uint256 rangeAmount0;
uint256 rangeAmount1;
}
/// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay to the pool for the minted liquidity.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
/// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap.
/// @dev In the implementation you must pay to the pool for swap.
/// @param amount0Delta The amount of token0 due to the pool for the swap
/// @param amount1Delta The amount of token1 due to the pool for the swap
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
/// @notice Returns the user position information associated with a given token ID.
/// @param tokenId The ID of the token that represents the position
/// @return Position
/// - nonce The nonce for permits
/// - pool Address of the uniswap V3 pool
/// - liquidity The liquidity of the position
/// - feeGrowth0 The fee growth of token0 as of the last action on the individual position
/// - feeGrowth1 The fee growth of token1 as of the last action on the individual position
/// - tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// - tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function userPositions(uint256 tokenId) external view returns (Position memory);
/// @notice Returns the vault information of unipilot base & range orders
/// @param pool Address of the Uniswap pool
/// @return LiquidityPosition
/// - baseTickLower The lower tick of the base position
/// - baseTickUpper The upper tick of the base position
/// - baseLiquidity The total liquidity of the base position
/// - rangeTickLower The lower tick of the range position
/// - rangeTickUpper The upper tick of the range position
/// - rangeLiquidity The total liquidity of the range position
/// - fees0 Total amount of fees collected by unipilot positions in terms of token0
/// - fees1 Total amount of fees collected by unipilot positions in terms of token1
/// - feeGrowthGlobal0 The fee growth of token0 collected per unit of liquidity for
/// the entire life of the unipilot vault
/// - feeGrowthGlobal1 The fee growth of token1 collected per unit of liquidity for
/// the entire life of the unipilot vault
/// - totalLiquidity Total amount of liquidity of vault including base & range orders
function poolPositions(address pool) external view returns (LiquidityPosition memory);
/// @notice Calculates the vault's total holdings of token0 and token1 - in
/// other words, how much of each token the vault would hold if it withdrew
/// all its liquidity from Uniswap.
/// @param _pool Address of the uniswap pool
/// @return amount0 Total amount of token0 in vault
/// @return amount1 Total amount of token1 in vault
/// @return totalLiquidity Total liquidity of the vault
function updatePositionTotalAmounts(address _pool)
external
view
returns (
uint256 amount0,
uint256 amount1,
uint256 totalLiquidity
);
/// @notice Calculates the vault's total holdings of TOKEN0 and TOKEN1 - in
/// other words, how much of each token the vault would hold if it withdrew
/// all its liquidity from Uniswap.
/// @dev Updates the position and return the latest reserves & liquidity.
/// @param token0 token0 of the pool
/// @param token0 token1 of the pool
/// @param data any necessary data needed to get reserves
/// @return totalAmount0 Amount of token0 in the pool of unipilot
/// @return totalAmount1 Amount of token1 in the pool of unipilot
/// @return totalLiquidity Total liquidity available in unipilot pool
function getReserves(
address token0,
address token1,
bytes calldata data
)
external
returns (
uint256 totalAmount0,
uint256 totalAmount1,
uint256 totalLiquidity
);
/// @notice Creates a new pool & then initializes the pool
/// @param _token0 The contract address of token0 of the pool
/// @param _token1 The contract address of token1 of the pool
/// @param data Necessary data needed to create pool
/// In data we will provide the `fee` amount of the v3 pool for the specified token pair,
/// also `sqrtPriceX96` The initial square root price of the pool
/// @return _pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address
function createPair(
address _token0,
address _token1,
bytes memory data
) external returns (address _pool);
/// @notice Deposits tokens in proportion to the Unipilot's current ticks, mints them
/// `Unipilot`s NFT.
/// @param token0 The first of the two tokens of the pool, sorted by address
/// @param token1 The second of the two tokens of the pool, sorted by address
/// @param amount0Desired Max amount of token0 to deposit
/// @param amount1Desired Max amount of token1 to deposit
/// @param shares Number of shares minted
/// @param tokenId Token Id of Unipilot
/// @param isTokenMinted Boolean to check the minting of new tokenId of Unipilot
/// @param data Necessary data needed to deposit
function deposit(
address token0,
address token1,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 shares,
uint256 tokenId,
bool isTokenMinted,
bytes memory data
) external payable;
/// @notice withdraws the desired shares from the vault with accumulated user fees and transfers to recipient.
/// @param pilotToken whether to recieve fees in PILOT or not (valid if user is not reciving fees in token0, token1)
/// @param wethToken whether to recieve fees in WETH or ETH (only valid for WETH/ALT pairs)
/// @param liquidity The amount by which liquidity will be withdrawn
/// @param tokenId The ID of the token for which liquidity is being withdrawn
/// @param data Necessary data needed to withdraw liquidity from Unipilot
function withdraw(
bool pilotToken,
bool wethToken,
uint256 liquidity,
uint256 tokenId,
bytes memory data
) external payable;
/// @notice Collects up to a maximum amount of fees owed to a specific user position to the recipient
/// @dev User have both options whether to recieve fees in PILOT or in pool token0 & token1
/// @param pilotToken whether to recieve fees in PILOT or not (valid if user is not reciving fees in token0, token1)
/// @param wethToken whether to recieve fees in WETH or ETH (only valid for WETH/ALT pairs)
/// @param tokenId The ID of the Unpilot NFT for which tokens will be collected
/// @param data Necessary data needed to collect fees from Unipilot
function collect(
bool pilotToken,
bool wethToken,
uint256 tokenId,
bytes memory data
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "./IHandler.sol";
interface IUnipilot {
struct DepositVars {
uint256 totalAmount0;
uint256 totalAmount1;
uint256 totalLiquidity;
uint256 shares;
uint256 amount0;
uint256 amount1;
}
function governance() external view returns (address);
function mintPilot(address recipient, uint256 amount) external;
function mintUnipilotNFT(address sender) external returns (uint256 mintedTokenId);
function deposit(IHandler.DepositParams memory params, bytes memory data)
external
payable
returns (
uint256 amount0Base,
uint256 amount1Base,
uint256 amount0Range,
uint256 amount1Range,
uint256 mintedTokenId
);
function createPoolAndDeposit(
IHandler.DepositParams memory params,
bytes[2] calldata data
)
external
payable
returns (
uint256 amount0Base,
uint256 amount1Base,
uint256 amount0Range,
uint256 amount1Range,
uint256 mintedTokenId
);
}
//SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
interface IUnipilotFarmV1 {
struct PoolInfo {
uint256 startBlock;
uint256 globalReward;
uint256 lastRewardBlock;
uint256 totalLockedLiquidity;
uint256 rewardMultiplier;
bool isRewardActive;
bool isAltActive;
}
function poolInfo(address pool) external view returns (PoolInfo memory);
}
//SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
interface IUnipilotStake {
function getBoostMultiplier(
address userAddress,
address poolAddress,
uint256 tokenId
) external view returns (uint256);
function userMultiplier(address userAddress, address poolAddress)
external
view
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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.7.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
abstract contract ReentrancyGuard {
uint8 private _unlocked = 1;
modifier nonReentrant() {
require(_unlocked == 1, "ReentrancyGuard: reentrant call");
_unlocked = 0;
_;
_unlocked = 1;
}
}
//SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
interface IULMEvents {
event PoolCreated(
address indexed token0,
address indexed token1,
address indexed pool,
uint24 fee,
uint160 sqrtPriceX96
);
event PoolReajusted(
address pool,
uint128 baseLiquidity,
uint128 rangeLiquidity,
int24 newBaseTickLower,
int24 newBaseTickUpper,
int24 newRangeTickLower,
int24 newRangeTickUpper
);
event Deposited(
address indexed pool,
uint256 tokenId,
uint256 amount0,
uint256 amount1,
uint256 liquidity
);
event Collect(
uint256 tokenId,
uint256 userAmount0,
uint256 userAmount1,
uint256 pilotAmount,
address pool,
address recipient
);
event Withdrawn(
address indexed pool,
address indexed recipient,
uint256 tokenId,
uint256 amount0,
uint256 amount1
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
/// @notice IHandler is a generalized interface for all the liquidity managers
/// @dev Contains all necessary methods that should be available in liquidity manager contracts
interface IHandler {
struct DepositParams {
address sender;
address exchangeAddress;
address token0;
address token1;
uint256 amount0Desired;
uint256 amount1Desired;
}
struct WithdrawParams {
bool pilotToken;
bool wethToken;
address exchangeAddress;
uint256 liquidity;
uint256 tokenId;
}
struct CollectParams {
bool pilotToken;
bool wethToken;
address exchangeAddress;
uint256 tokenId;
}
function createPair(
address _token0,
address _token1,
bytes calldata data
) external;
function deposit(
address token0,
address token1,
address sender,
uint256 amount0,
uint256 amount1,
uint256 shares,
bytes calldata data
)
external
returns (
uint256 amount0Base,
uint256 amount1Base,
uint256 amount0Range,
uint256 amount1Range,
uint256 mintedTokenId
);
function withdraw(
bool pilotToken,
bool wethToken,
uint256 liquidity,
uint256 tokenId,
bytes calldata data
) external;
function getReserves(
address token0,
address token1,
bytes calldata data
)
external
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
);
function collect(
bool pilotToken,
bool wethToken,
uint256 tokenId,
bytes calldata data
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
|
withdraw NFT without reward claiming _tokenId unstake this tokenID
|
function emergencyNFTWithdraw(uint256 _tokenId) external {
UserInfo storage userState = userInfo[_tokenId];
require(userState.user == msg.sender, "NOO");
PoolInfo storage poolState = poolInfo[userState.pool];
PoolAltInfo storage poolAltState = poolAltInfo[userState.pool];
poolState.totalLockedLiquidity = poolState.totalLockedLiquidity.sub(
userState.liquidity
);
IERC721(UNIPILOT).safeTransferFrom(address(this), userState.user, _tokenId);
if (poolState.totalLockedLiquidity == 0) {
poolState.startBlock = block.number;
poolState.lastRewardBlock = block.number;
poolState.globalReward = 0;
poolAltState.startBlock = block.number;
poolAltState.lastRewardBlock = block.number;
poolAltState.globalReward = 0;
}
uint256 index = callIndex(userState.pool, _tokenId);
updateNFTList(index, userState.user, userState.pool);
delete userInfo[_tokenId];
}
| 7,228,763 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// 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 "../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.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);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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 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);
}
/**
*Submitted for verification at Etherscan.io on 2021-08-08
*/
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// SPDX-License-Identifier: MIT
// File contracts/BMWU/bmwu.sol
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
pragma solidity ^0.8.0;
contract WorldOfSquish is ERC721URIStorage, Ownable{
using Strings for uint256;
event MintSquish (address indexed sender, uint256 startWith, uint256 times);
uint256 public totalSquish;
uint256 public totalCount = 9980;
uint256 public maxBatch = 40;
uint256 public price = 50000000000000000; // 0.05 eth
string public baseURI;
bool private started;
constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) {
baseURI = baseURI_;
}
function totalSupply() public view virtual returns (uint256) {
return totalSquish;
}
function _baseURI() internal view virtual override returns (string memory){
return baseURI;
}
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
function changePrice(uint256 _newPrice) public onlyOwner {
price = _newPrice;
}
function changeBatchSize(uint256 _newBatch) public onlyOwner {
maxBatch = _newBatch;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token.");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : '.json';
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
function setStart(bool _start) public onlyOwner {
started = _start;
}
function mintSquish(uint256 _times) payable public {
require(started, "not started");
require(_times >0 && _times <= maxBatch, "wake wrong number");
require(totalSquish + _times <= totalCount, "wake too much");
require(msg.value == _times * price, "value error");
payable(owner()).transfer(msg.value);
emit MintSquish(_msgSender(), totalSquish+1, _times);
for(uint256 i=0; i< _times; i++){
_mint(_msgSender(), 1 + totalSquish++);
}
}
}
|
See {IERC721Metadata-tokenURI}./ If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
import "../ERC721.sol";
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 (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
| 24,004 |
pragma solidity 0.4.24;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Burn(address indexed from, uint value);
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
owner = newOwner;
newOwner = address(0);
emit OwnershipTransferred(owner, newOwner);
}
}
contract Pausable is Owned {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract OxyCoin is ERC20Interface, Owned, Pausable {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "OXY";
name = "Oxycoin";
decimals = 18;
_totalSupply = 1200000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
modifier onlyPayloadSize(uint numWords) {
assert(msg.data.length >= numWords * 32 + 4);
_;
}
/**
* @dev function to check whether passed address is a contract address
*/
function isContract(address _address) private view returns (bool is_contract) {
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_address)
}
return (length > 0);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param tokenOwner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param tokenOwner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param tokens The amount to be transferred.
*/
function transfer(address to, uint tokens) public whenNotPaused onlyPayloadSize(2) returns (bool success) {
require(to != address(0));
require(tokens > 0);
require(tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
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 tokens The amount of tokens to be spent.
*/
function approve(address spender, uint tokens) public whenNotPaused onlyPayloadSize(2) returns (bool success) {
require(spender != address(0));
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param tokens uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint tokens) public whenNotPaused onlyPayloadSize(3) returns (bool success) {
require(tokens > 0);
require(from != address(0));
require(to != address(0));
require(allowed[from][msg.sender] > 0);
require(balances[from]>0);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
_totalSupply =_totalSupply.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint _value) public returns (bool success) {
require(balances[from] >= _value);
require(_value <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(_value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(from, _value);
return true;
}
/**
* @dev Function to mint tokens
* @param target The address that will receive the minted tokens.
* @param mintedAmount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mintToken(address target, uint mintedAmount) onlyOwner public returns (bool) {
require(mintedAmount > 0);
require(target != address(0));
balances[target] = balances[target].add(mintedAmount);
_totalSupply = _totalSupply.add(mintedAmount);
emit Transfer(owner, target, mintedAmount);
return true;
}
function () public payable {
revert();
}
/**
* @dev Function to transfer any ERC20 token to owner address which gets accidentally transferred to this contract
* @param tokenAddress The address of the ERC20 contract
* @param tokens The amount of tokens to transfer.
* @return A boolean that indicates if the operation was successful.
*/
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
require(tokenAddress != address(0));
require(isContract(tokenAddress));
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
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: spender The address which will spend the funds. tokens The amount of tokens to be spent./
|
function approve(address spender, uint tokens) public whenNotPaused onlyPayloadSize(2) returns (bool success) {
require(spender != address(0));
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| 7,030,365 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "../interfaces/Controller.sol";
import "../interfaces/Aave.sol";
contract yDelegatedVault is ERC20 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
address public governance;
address public controller;
uint public insurance;
uint public healthFactor = 4;
uint public ltv = 65;
uint public max = 100;
address public constant aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor (address _token, address _controller) public ERC20(
string(abi.encodePacked("yearn ", ERC20(_token).name())),
string(abi.encodePacked("y", ERC20(_token).symbol()))
) {
_setupDecimals(ERC20(_token).decimals());
token = IERC20(_token);
governance = msg.sender;
controller = _controller;
}
function debt() public view returns (uint) {
address _reserve = Controller(controller).want(address(this));
(,uint currentBorrowBalance,,,,,,,,) = Aave(getAave()).getUserReserveData(_reserve, address(this));
return currentBorrowBalance;
}
function credit() public view returns (uint) {
return Controller(controller).balanceOf(address(this));
}
// % of tokens locked and cannot be withdrawn per user
// this is impermanent locked, unless the debt out accrues the strategy
function locked() public view returns (uint) {
return credit().mul(1e18).div(debt());
}
function debtShare(address _lp) public view returns (uint) {
return debt().mul(balanceOf(_lp)).mul(totalSupply());
}
function getAave() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPool();
}
function getAaveCore() public view returns (address) {
return LendingPoolAddressesProvider(aave).getLendingPoolCore();
}
function setHealthFactor(uint _hf) external {
require(msg.sender == governance, "!governance");
healthFactor = _hf;
}
function activate() public {
Aave(getAave()).setUserUseReserveAsCollateral(underlying(), true);
}
function repay(address reserve, uint amount) public {
// Required for certain stable coins (USDT for example)
IERC20(reserve).approve(address(getAaveCore()), 0);
IERC20(reserve).approve(address(getAaveCore()), amount);
Aave(getAave()).repay(reserve, amount, address(uint160(address(this))));
}
function repayAll() public {
address _reserve = reserve();
uint _amount = IERC20(_reserve).balanceOf(address(this));
repay(_reserve, _amount);
}
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function harvest(address reserve, uint amount) external {
require(msg.sender == controller, "!controller");
require(reserve != address(token), "token");
IERC20(reserve).safeTransfer(controller, amount);
}
// Ignore insurance fund for balance calculations
function balance() public view returns (uint) {
return token.balanceOf(address(this)).sub(insurance);
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setController(address _controller) external {
require(msg.sender == governance, "!governance");
controller = _controller;
}
function getAaveOracle() public view returns (address) {
return LendingPoolAddressesProvider(aave).getPriceOracle();
}
function getReservePriceETH(address reserve) public view returns (uint) {
return Oracle(getAaveOracle()).getAssetPrice(reserve);
}
function shouldRebalance() external view returns (bool) {
return (over() > 0);
}
function over() public view returns (uint) {
over(0);
}
function getUnderlyingPriceETH(uint _amount) public view returns (uint) {
_amount = _amount.mul(getUnderlyingPrice()).div(uint(10)**ERC20(address(token)).decimals()); // Calculate the amount we are withdrawing in ETH
return _amount.mul(ltv).div(max).div(healthFactor);
}
function over(uint _amount) public view returns (uint) {
address _reserve = reserve();
uint _eth = getUnderlyingPriceETH(_amount);
(uint _maxSafeETH,uint _totalBorrowsETH,) = maxSafeETH();
_maxSafeETH = _maxSafeETH.mul(105).div(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_eth > _maxSafeETH) {
_maxSafeETH = 0;
} else {
_maxSafeETH = _maxSafeETH.sub(_eth); // Add the ETH we are withdrawing
}
if (_maxSafeETH < _totalBorrowsETH) {
uint _over = _totalBorrowsETH.mul(_totalBorrowsETH.sub(_maxSafeETH)).div(_totalBorrowsETH);
_over = _over.mul(uint(10)**ERC20(_reserve).decimals()).div(getReservePrice());
return _over;
} else {
return 0;
}
}
function _rebalance(uint _amount) internal {
uint _over = over(_amount);
if (_over > 0) {
if (_over > credit()) {
_over = credit();
}
if (_over > 0) {
Controller(controller).withdraw(address(this), _over);
repayAll();
}
}
}
function rebalance() external {
_rebalance(0);
}
function claimInsurance() external {
require(msg.sender == controller, "!controller");
token.safeTransfer(controller, insurance);
insurance = 0;
}
function maxSafeETH() public view returns (uint maxBorrowsETH, uint totalBorrowsETH, uint availableBorrowsETH) {
(,,uint _totalBorrowsETH,,uint _availableBorrowsETH,,,) = Aave(getAave()).getUserAccountData(address(this));
uint _maxBorrowETH = (_totalBorrowsETH.add(_availableBorrowsETH));
return (_maxBorrowETH.div(healthFactor), _totalBorrowsETH, _availableBorrowsETH);
}
function shouldBorrow() external view returns (bool) {
return (availableToBorrowReserve() > 0);
}
function availableToBorrowETH() public view returns (uint) {
(uint _maxSafeETH,uint _totalBorrowsETH, uint _availableBorrowsETH) = maxSafeETH();
_maxSafeETH = _maxSafeETH.mul(95).div(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_maxSafeETH > _totalBorrowsETH) {
return _availableBorrowsETH.mul(_maxSafeETH.sub(_totalBorrowsETH)).div(_availableBorrowsETH);
} else {
return 0;
}
}
function availableToBorrowReserve() public view returns (uint) {
address _reserve = reserve();
uint _available = availableToBorrowETH();
if (_available > 0) {
return _available.mul(uint(10)**ERC20(_reserve).decimals()).div(getReservePrice());
} else {
return 0;
}
}
function getReservePrice() public view returns (uint) {
return getReservePriceETH(reserve());
}
function getUnderlyingPrice() public view returns (uint) {
return getReservePriceETH(underlying());
}
function earn() external {
address _reserve = reserve();
uint _borrow = availableToBorrowReserve();
if (_borrow > 0) {
Aave(getAave()).borrow(_reserve, _borrow, 2, 7);
}
//rebalance here
uint _balance = IERC20(_reserve).balanceOf(address(this));
if (_balance > 0) {
IERC20(_reserve).safeTransfer(controller, _balance);
Controller(controller).earn(address(this), _balance);
}
}
function depositAll() external {
deposit(token.balanceOf(msg.sender));
}
function deposit(uint _amount) public {
uint _pool = balance();
token.safeTransferFrom(msg.sender, address(this), _amount);
// 0.5% of deposits go into an insurance fund incase of negative profits to protect withdrawals
// At a 4 health factor, this is a -2% position
uint _insurance = _amount.mul(50).div(10000);
_amount = _amount.sub(_insurance);
insurance = insurance.add(_insurance);
//Controller can claim insurance to liquidate to cover interest
uint shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
}
function reserve() public view returns (address) {
return Controller(controller).want(address(this));
}
function underlying() public view returns (address) {
return AaveToken(address(token)).underlyingAssetAddress();
}
function withdrawAll() public {
withdraw(balanceOf(msg.sender));
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint _shares) public {
uint r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
_rebalance(r);
token.safeTransfer(msg.sender, r);
}
function getPricePerFullShare() external view returns (uint) {
return balance().mul(1e18).div(totalSupply());
}
}
|
0.5% of deposits go into an insurance fund incase of negative profits to protect withdrawals At a 4 health factor, this is a -2% positionController can claim insurance to liquidate to cover interest
|
function deposit(uint _amount) public {
uint _pool = balance();
token.safeTransferFrom(msg.sender, address(this), _amount);
uint _insurance = _amount.mul(50).div(10000);
_amount = _amount.sub(_insurance);
insurance = insurance.add(_insurance);
uint shares = 0;
if (totalSupply() == 0) {
shares = _amount;
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
}
| 12,682,234 |
// Project: AleHub
// v1, 2018-05-24
// This code is the property of CryptoB2B.io
// Copying in whole or in part is prohibited.
// Authors: Ivan Fedorov and Dmitry Borodin
// Do you want the same TokenSale platform? www.cryptob2b.io
// *.sol in 1 file - https://cryptob2b.io/solidity/alehub/
pragma solidity ^0.4.21;
contract GuidedByRoles {
IRightAndRoles public rightAndRoles;
function GuidedByRoles(IRightAndRoles _rightAndRoles) public {
rightAndRoles = _rightAndRoles;
}
}
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) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function minus(uint256 a, uint256 b) internal pure returns (uint256) {
if (b>=a) return 0;
return a - b;
}
}
contract Crowdsale is GuidedByRoles{
// (A1)
// The main contract for the sale and management of rounds.
// 0000000000000000000000000000000000000000000000000000000000000000
uint256 constant USER_UNPAUSE_TOKEN_TIMEOUT = 60 days;
uint256 constant FORCED_REFUND_TIMEOUT1 = 400 days;
uint256 constant FORCED_REFUND_TIMEOUT2 = 600 days;
uint256 constant ROUND_PROLONGATE = 60 days;
uint256 constant BURN_TOKENS_TIME = 90 days;
using SafeMath for uint256;
enum TokenSaleType {round1, round2}
TokenSaleType public TokenSale = TokenSaleType.round1;
ICreator public creator;
bool isBegin=false;
IToken public token;
IAllocation public allocation;
IFinancialStrategy public financialStrategy;
bool public isFinalized;
bool public isInitialized;
bool public isPausedCrowdsale;
bool public chargeBonuses;
bool public canFirstMint=true;
struct Bonus {
uint256 value;
uint256 procent;
uint256 freezeTime;
}
struct Profit {
uint256 percent;
uint256 duration;
}
struct Freezed {
uint256 value;
uint256 dateTo;
}
Bonus[] public bonuses;
Profit[] public profits;
uint256 public startTime= 1527206400;
uint256 public endTime = 1529971199;
uint256 public renewal;
// How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH
// **THOUSANDS** 10^18 for human, *10**18 for Solidity, 1e18 for MyEtherWallet (MEW).
// Example: if 1ETH = 40.5 Token ==> use 40500 finney
uint256 public rate = 2333 ether; // $0.1 (ETH/USD=$500)
// ETH/USD rate in US$
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: ETH/USD=$1000 ==> use 1000*10**18 (Solidity) or 1000 ether or 1000e18 (MEW)
uint256 public exchange = 700 ether;
// If the round does not attain this value before the closing date, the round is recognized as a
// failure and investors take the money back (the founders will not interfere in any way).
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: softcap=15ETH ==> use 15*10**18 (Solidity) or 15e18 (MEW)
uint256 public softCap = 0;
// The maximum possible amount of income
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450*10**15 (Solidity) or 12345e15 (MEW)
uint256 public hardCap = 4285 ether; // $31M (ETH/USD=$500)
// If the last payment is slightly higher than the hardcap, then the usual contracts do
// not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the
// last payment, very slightly raising the hardcap. The value indicates by how many ETH the
// last payment can exceed the hardcap to allow it to be paid. Immediately after this payment, the
// round closes. The funders should write here a small number, not more than 1% of the CAP.
// Can be equal to zero, to cancel.
// **QUINTILLIONS** 10^18 / *10**18 / 1e18
uint256 public overLimit = 20 ether;
// The minimum possible payment from an investor in ETH. Payments below this value will be rejected.
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: minPay=0.1ETH ==> use 100*10**15 (Solidity) or 100e15 (MEW)
uint256 public minPay = 43 finney;
uint256 public maxAllProfit = 40; // max time bonus=20%, max value bonus=10%, maxAll=10%+20%
uint256 public ethWeiRaised;
uint256 public nonEthWeiRaised;
uint256 public weiRound1;
uint256 public tokenReserved;
uint256 public totalSaledToken;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
event Initialized();
event PaymentedInOtherCurrency(uint256 token, uint256 value);
event ExchangeChanged(uint256 indexed oldExchange, uint256 indexed newExchange);
function Crowdsale(ICreator _creator,IToken _token) GuidedByRoles(_creator.getRightAndRoles()) public
{
creator=_creator;
token = _token;
}
// Setting the current rate ETH/USD
// function changeExchange(uint256 _ETHUSD) public {
// require(rightAndRoles.onlyRoles(msg.sender,18));
// require(_ETHUSD >= 1 ether);
// emit ExchangeChanged(exchange,_ETHUSD);
// softCap=softCap.mul(exchange).div(_ETHUSD); // QUINTILLIONS
// hardCap=hardCap.mul(exchange).div(_ETHUSD); // QUINTILLIONS
// minPay=minPay.mul(exchange).div(_ETHUSD); // QUINTILLIONS
//
// rate=rate.mul(_ETHUSD).div(exchange); // QUINTILLIONS
//
// for (uint16 i = 0; i < bonuses.length; i++) {
// bonuses[i].value=bonuses[i].value.mul(exchange).div(_ETHUSD); // QUINTILLIONS
// }
// bytes32[] memory params = new bytes32[](2);
// params[0] = bytes32(exchange);
// params[1] = bytes32(_ETHUSD);
// financialStrategy.setup(5, params);
//
// exchange=_ETHUSD;
//
// }
// Setting of basic parameters, analog of class constructor
// @ Do I have to use the function see your scenario
// @ When it is possible to call before Round 1/2
// @ When it is launched automatically -
// @ Who can call the function admins
function begin() public
{
require(rightAndRoles.onlyRoles(msg.sender,22));
if (isBegin) return;
isBegin=true;
financialStrategy = creator.createFinancialStrategy();
token.setUnpausedWallet(rightAndRoles.wallets(1,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(3,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(4,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(5,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(6,0), true);
bonuses.push(Bonus(1429 finney, 2,0));
bonuses.push(Bonus(14286 finney, 5,0));
bonuses.push(Bonus(142857 finney, 10,0));
profits.push(Profit(25,100 days));
}
// Issue of tokens for the zero round, it is usually called: private pre-sale (Round 0)
// @ Do I have to use the function may be
// @ When it is possible to call before Round 1/2
// @ When it is launched automatically -
// @ Who can call the function admins
function firstMintRound0(uint256 _amount /* QUINTILLIONS! */) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(canFirstMint);
begin();
token.mint(rightAndRoles.wallets(3,0),_amount);
}
// info
function totalSupply() external view returns (uint256){
return token.totalSupply();
}
// Returns the name of the current round in plain text. Constant.
function getTokenSaleType() external view returns(string){
return (TokenSale == TokenSaleType.round1)?'round1':'round2';
}
// Transfers the funds of the investor to the contract of return of funds. Internal.
function forwardFunds(address _beneficiary) internal {
financialStrategy.deposit.value(msg.value)(_beneficiary);
}
// Check for the possibility of buying tokens. Inside. Constant.
function validPurchase() internal view returns (bool) {
// The round started and did not end
bool withinPeriod = (now > startTime && now < endTime.add(renewal));
// Rate is greater than or equal to the minimum
bool nonZeroPurchase = msg.value >= minPay;
// hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit
bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit);
// round is initialized and no "Pause of trading" is set
return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isFinalized && !isPausedCrowdsale;
}
// Check for the ability to finalize the round. Constant.
function hasEnded() public view returns (bool) {
bool isAdmin = rightAndRoles.onlyRoles(msg.sender,6);
bool timeReached = now > endTime.add(renewal);
bool capReached = weiRaised() >= hardCap;
return (timeReached || capReached || (isAdmin && goalReached())) && isInitialized && !isFinalized;
}
// Finalize. Only available to the Manager and the Beneficiary. If the round failed, then
// anyone can call the finalization to unlock the return of funds to investors
// You must call a function to finalize each round (after the Round1 & after the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call after end of Round1 & Round2
// @ When it is launched automatically no
// @ Who can call the function admins or anybody (if round is failed)
function finalize() public {
// bool isAdmin = rightAndRoles.onlyRoles(msg.sender,6);
// require(isAdmin|| !goalReached());
// require(!isFinalized && isInitialized);
// require(hasEnded() || (isAdmin && goalReached()));
require(hasEnded());
isFinalized = true;
finalization();
emit Finalized();
}
// The logic of finalization. Internal
// @ Do I have to use the function no
// @ When it is possible to call -
// @ When it is launched automatically after end of round
// @ Who can call the function -
function finalization() internal {
bytes32[] memory params = new bytes32[](0);
// If the goal of the achievement
if (goalReached()) {
financialStrategy.setup(1,params);//Для контракта Buz деньги не возвращает.
// if there is anything to give
if (tokenReserved > 0) {
token.mint(rightAndRoles.wallets(3,0),tokenReserved);
// Reset the counter
tokenReserved = 0;
}
// If the finalization is Round 1
if (TokenSale == TokenSaleType.round1) {
// Reset settings
isInitialized = false;
isFinalized = false;
if(financialStrategy.freeCash() == 0){
rightAndRoles.setManagerPowerful(true);
}
// Switch to the second round (to Round2)
TokenSale = TokenSaleType.round2;
// Reset the collection counter
weiRound1 = weiRaised();
ethWeiRaised = 0;
nonEthWeiRaised = 0;
}
else // If the second round is finalized
{
// Permission to collect tokens to those who can pick them up
chargeBonuses = true;
totalSaledToken = token.totalSupply();
//partners = true;
}
}
else // If they failed round
{
financialStrategy.setup(3,params);
}
}
// The Manager freezes the tokens for the Team.
// You must call a function to finalize Round 2 (only after the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call Round2
// @ When it is launched automatically -
// @ Who can call the function admins
function finalize2() public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(chargeBonuses);
chargeBonuses = false;
allocation = creator.createAllocation(token, now + 1 years /* stage N1 */,0/* not need*/);
token.setUnpausedWallet(allocation, true);
// Team = %, Founders = %, Fund = % TOTAL = %
allocation.addShare(rightAndRoles.wallets(7,0),100,100); // all 100% - first year
//allocation.addShare(wallets[uint8(Roles.founders)], 10, 50); // only 50% - first year, stage N1 (and +50 for stage N2)
// 2% - bounty wallet
token.mint(rightAndRoles.wallets(5,0), totalSaledToken.mul(2).div(77));
// 10% - company
token.mint(rightAndRoles.wallets(6,0), totalSaledToken.mul(10).div(77));
// 13% - team
token.mint(allocation, totalSaledToken.mul(11).div(77));
}
// Initializing the round. Available to the manager. After calling the function,
// the Manager loses all rights: Manager can not change the settings (setup), change
// wallets, prevent the beginning of the round, etc. You must call a function after setup
// for the initial round (before the Round1 and before the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call before each round
// @ When it is launched automatically -
// @ Who can call the function admins
function initialize() public {
require(rightAndRoles.onlyRoles(msg.sender,6));
// If not yet initialized
require(!isInitialized);
begin();
// And the specified start time has not yet come
// If initialization return an error, check the start date!
require(now <= startTime);
initialization();
emit Initialized();
renewal = 0;
isInitialized = true;
canFirstMint = false;
}
function initialization() internal {
bytes32[] memory params = new bytes32[](0);
rightAndRoles.setManagerPowerful(false);
if (financialStrategy.state() != IFinancialStrategy.State.Active){
financialStrategy.setup(2,params);
}
}
//
// @ Do I have to use the function
// @ When it is possible to call
// @ When it is launched automatically
// @ Who can call the function
function getPartnerCash(uint8 _user, bool _calc) external {
if(_calc)
calcFin();
financialStrategy.getPartnerCash(_user, msg.sender);
}
function getBeneficiaryCash(bool _calc) public {
require(rightAndRoles.onlyRoles(msg.sender,22));
if(_calc)
calcFin();
financialStrategy.getBeneficiaryCash();
if(!isInitialized && financialStrategy.freeCash() == 0)
rightAndRoles.setManagerPowerful(true);
}
function claimRefund() external{
financialStrategy.refund(msg.sender);
}
function calcFin() public {
bytes32[] memory params = new bytes32[](2);
params[0] = bytes32(weiTotalRaised());
params[1] = bytes32(msg.sender);
financialStrategy.setup(4,params);
}
function calcAndGet() public {
require(rightAndRoles.onlyRoles(msg.sender,22));
getBeneficiaryCash(true);
for (uint8 i=0; i<0; i++) { // <-- TODO check financialStrategy.wallets.length
financialStrategy.getPartnerCash(i, msg.sender);
}
}
// We check whether we collected the necessary minimum funds. Constant.
function goalReached() public view returns (bool) {
return weiRaised() >= softCap;
}
// Customize. The arguments are described in the constructor above.
// @ Do I have to use the function yes
// @ When it is possible to call before each rond
// @ When it is launched automatically -
// @ Who can call the function admins
function setup(uint256 _startTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap,
uint256 _rate, uint256 _exchange,
uint256 _maxAllProfit, uint256 _overLimit, uint256 _minPay,
uint256[] _durationTB , uint256[] _percentTB, uint256[] _valueVB, uint256[] _percentVB, uint256[] _freezeTimeVB) public
{
require(rightAndRoles.onlyRoles(msg.sender,6));
require(!isInitialized);
begin();
// Date and time are correct
require(now <= _startTime);
require(_startTime < _endTime);
startTime = _startTime;
endTime = _endTime;
// The parameters are correct
require(_softCap <= _hardCap);
softCap = _softCap;
hardCap = _hardCap;
require(_rate > 0);
rate = _rate;
overLimit = _overLimit;
minPay = _minPay;
exchange = _exchange;
maxAllProfit = _maxAllProfit;
require(_valueVB.length == _percentVB.length && _valueVB.length == _freezeTimeVB.length);
bonuses.length = _valueVB.length;
for(uint256 i = 0; i < _valueVB.length; i++){
bonuses[i] = Bonus(_valueVB[i],_percentVB[i],_freezeTimeVB[i]);
}
require(_percentTB.length == _durationTB.length);
profits.length = _percentTB.length;
for( i = 0; i < _percentTB.length; i++){
profits[i] = Profit(_percentTB[i],_durationTB[i]);
}
}
// Collected funds for the current round. Constant.
function weiRaised() public constant returns(uint256){
return ethWeiRaised.add(nonEthWeiRaised);
}
// Returns the amount of fees for both phases. Constant.
function weiTotalRaised() public constant returns(uint256){
return weiRound1.add(weiRaised());
}
// Returns the percentage of the bonus on the current date. Constant.
function getProfitPercent() public constant returns (uint256){
return getProfitPercentForData(now);
}
// Returns the percentage of the bonus on the given date. Constant.
function getProfitPercentForData(uint256 _timeNow) public constant returns (uint256){
uint256 allDuration;
for(uint8 i = 0; i < profits.length; i++){
allDuration = allDuration.add(profits[i].duration);
if(_timeNow < startTime.add(allDuration)){
return profits[i].percent;
}
}
return 0;
}
function getBonuses(uint256 _value) public constant returns (uint256,uint256,uint256){
if(bonuses.length == 0 || bonuses[0].value > _value){
return (0,0,0);
}
uint16 i = 1;
for(i; i < bonuses.length; i++){
if(bonuses[i].value > _value){
break;
}
}
return (bonuses[i-1].value,bonuses[i-1].procent,bonuses[i-1].freezeTime);
}
// The ability to quickly check Round1 (only for Round1, only 1 time). Completes the Round1 by
// transferring the specified number of tokens to the Accountant's wallet. Available to the Manager.
// Use only if this is provided by the script and white paper. In the normal scenario, it
// does not call and the funds are raised normally. We recommend that you delete this
// function entirely, so as not to confuse the auditors. Initialize & Finalize not needed.
// ** QUINTILIONS ** 10^18 / 1**18 / 1e18
// @ Do I have to use the function no, see your scenario
// @ When it is possible to call after Round0 and before Round2
// @ When it is launched automatically -
// @ Who can call the function admins
// function fastTokenSale(uint256 _totalSupply) external {
// onlyAdmin(false);
// require(TokenSale == TokenSaleType.round1 && !isInitialized);
// token.mint(wallets[uint8(Roles.accountant)], _totalSupply);
// TokenSale = TokenSaleType.round2;
// }
// Remove the "Pause of exchange". Available to the manager at any time. If the
// manager refuses to remove the pause, then 30-120 days after the successful
// completion of the TokenSale, anyone can remove a pause and allow the exchange to continue.
// The manager does not interfere and will not be able to delay the term.
// He can only cancel the pause before the appointed time.
// @ Do I have to use the function YES YES YES
// @ When it is possible to call after end of ICO
// @ When it is launched automatically -
// @ Who can call the function admins or anybody
function tokenUnpause() external {
require(rightAndRoles.onlyRoles(msg.sender,2)
|| (now > endTime.add(renewal).add(USER_UNPAUSE_TOKEN_TIMEOUT) && TokenSale == TokenSaleType.round2 && isFinalized && goalReached()));
token.setPause(false);
}
// Enable the "Pause of exchange". Available to the manager until the TokenSale is completed.
// The manager cannot turn on the pause, for example, 3 years after the end of the TokenSale.
// @ Do I have to use the function no
// @ When it is possible to call while Round2 not ended
// @ When it is launched automatically before any rounds
// @ Who can call the function admins
function tokenPause() public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(!isFinalized);
token.setPause(true);
}
// Pause of sale. Available to the manager.
// @ Do I have to use the function no
// @ When it is possible to call during active rounds
// @ When it is launched automatically -
// @ Who can call the function admins
function setCrowdsalePause(bool mode) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
isPausedCrowdsale = mode;
}
// For example - After 5 years of the project's existence, all of us suddenly decided collectively
// (company + investors) that it would be more profitable for everyone to switch to another smart
// contract responsible for tokens. The company then prepares a new token, investors
// disassemble, study, discuss, etc. After a general agreement, the manager allows any investor:
// - to burn the tokens of the previous contract
// - generate new tokens for a new contract
// It is understood that after a general solution through this function all investors
// will collectively (and voluntarily) move to a new token.
// @ Do I have to use the function no
// @ When it is possible to call only after ICO!
// @ When it is launched automatically -
// @ Who can call the function admins
function moveTokens(address _migrationAgent) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
token.setMigrationAgent(_migrationAgent);
}
// @ Do I have to use the function no
// @ When it is possible to call only after ICO!
// @ When it is launched automatically -
// @ Who can call the function admins
function migrateAll(address[] _holders) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
token.migrateAll(_holders);
}
// The beneficiary at any time can take rights in all roles and prescribe his wallet in all the
// rollers. Thus, he will become the recipient of tokens for the role of Accountant,
// Team, etc. Works at any time.
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function only Beneficiary
// function resetAllWallets() external{
// address _beneficiary = wallets[uint8(Roles.beneficiary)];
// require(msg.sender == _beneficiary);
// for(uint8 i = 0; i < wallets.length; i++){
// wallets[i] = _beneficiary;
// }
// token.setUnpausedWallet(_beneficiary, true);
// }
// Burn the investor tokens, if provided by the ICO scenario. Limited time available - BURN_TOKENS_TIME
// For people who ignore the KYC/AML procedure during 30 days after payment: money back and burning tokens.
// ***CHECK***SCENARIO***
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function admin
function massBurnTokens(address[] _beneficiary, uint256[] _value) external {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(endTime.add(renewal).add(BURN_TOKENS_TIME) > now);
require(_beneficiary.length == _value.length);
for(uint16 i; i<_beneficiary.length; i++) {
token.burn(_beneficiary[i],_value[i]);
}
}
// Extend the round time, if provided by the script. Extend the round only for
// a limited number of days - ROUND_PROLONGATE
// ***CHECK***SCENARIO***
// @ Do I have to use the function no
// @ When it is possible to call during active round
// @ When it is launched automatically -
// @ Who can call the function admins
function prolong(uint256 _duration) external {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(now > startTime && now < endTime.add(renewal) && isInitialized && !isFinalized);
renewal = renewal.add(_duration);
require(renewal <= ROUND_PROLONGATE);
}
// If a little more than a year has elapsed (Round2 start date + 400 days), a smart contract
// will allow you to send all the money to the Beneficiary, if any money is present. This is
// possible if you mistakenly launch the Round2 for 30 years (not 30 days), investors will transfer
// money there and you will not be able to pick them up within a reasonable time. It is also
// possible that in our checked script someone will make unforeseen mistakes, spoiling the
// finalization. Without finalization, money cannot be returned. This is a rescue option to
// get around this problem, but available only after a year (400 days).
// Another reason - the TokenSale was a failure, but not all ETH investors took their money during the year after.
// Some investors may have lost a wallet key, for example.
// The method works equally with the Round1 and Round2. When the Round1 starts, the time for unlocking
// the distructVault begins. If the TokenSale is then started, then the term starts anew from the first day of the TokenSale.
// Next, act independently, in accordance with obligations to investors.
// Within 400 days (FORCED_REFUND_TIMEOUT1) of the start of the Round, if it fails only investors can take money. After
// the deadline this can also include the company as well as investors, depending on who is the first to use the method.
// @ Do I have to use the function no
// @ When it is possible to call -
// @ When it is launched automatically -
// @ Who can call the function beneficiary & manager
function distructVault() public {
bytes32[] memory params = new bytes32[](1);
params[0] = bytes32(msg.sender);
if (rightAndRoles.onlyRoles(msg.sender,4) && (now > startTime.add(FORCED_REFUND_TIMEOUT1))) {
financialStrategy.setup(0,params);
}
if (rightAndRoles.onlyRoles(msg.sender,2) && (now > startTime.add(FORCED_REFUND_TIMEOUT2))) {
financialStrategy.setup(0,params);
}
}
// We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC).
// Perhaps other types of cryptocurrency - see the original terms in the white paper and on the TokenSale website.
// We release tokens on Ethereum. During the Round1 and Round2 with a smart contract, you directly transfer
// the tokens there and immediately, with the same transaction, receive tokens in your wallet.
// When paying in any other currency, for example in BTC, we accept your money via one common wallet.
// Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart
// contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis.
// The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract
// monitors softcap and hardcap, so as not to go beyond this framework.
// In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several
// transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total.
// In this case, we will refund all the amounts above, in order not to exceed the hardcap.
// Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published
// everywhere (in a white paper, on the TokenSale website, on Telegram, on Bitcointalk, in this code, etc.)
// Anyone interested can check that the administrator of the smart contract writes down exactly the amount
// in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in
// BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to
// paymentsInOtherCurrency however, this threat is leveled.
// Any user can check the amounts in BTC and the variable of the smart contract that accounts for this
// (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract
// on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the TokenSale,
// simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection)
// and the actual transactions in BTC. The company strictly adheres to the described principles of openness.
// The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you
// cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as
// brakes on the Ethereum network, this operation may be difficult. You should only worry if the
// administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet
// receives significant amounts.
// This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap.
// ** QUINTILLIONS ** 10^18 / 1**18 / 1e18
// @ Do I have to use the function no
// @ When it is possible to call during active rounds
// @ When it is launched automatically every day from cryptob2b token software
// @ Who can call the function admins + observer
function paymentsInOtherCurrency(uint256 _token, uint256 _value) public {
// **For audit**
// BTC Wallet: 1D7qaRN6keGJKb5LracZYQEgCBaryZxVaE
// BCH Wallet: 1CDRdTwvEyZD7qjiGUYxZQSf8n91q95xHU
// DASH Wallet: XnjajDvQq1C7z2o4EFevRhejc6kRmX1NUp
// LTC Wallet: LhHkiwVfoYEviYiLXP5pRK2S1QX5eGrotA
require(rightAndRoles.onlyRoles(msg.sender,18));
//onlyAdmin(true);
bool withinPeriod = (now >= startTime && now <= endTime.add(renewal));
bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit);
require(withinPeriod && withinCap && isInitialized && !isFinalized);
emit PaymentedInOtherCurrency(_token,_value);
nonEthWeiRaised = _value;
tokenReserved = _token;
}
function lokedMint(address _beneficiary, uint256 _value, uint256 _freezeTime) internal {
if(_freezeTime > 0){
uint256 totalBloked = token.freezedTokenOf(_beneficiary).add(_value);
uint256 pastDateUnfreeze = token.defrostDate(_beneficiary);
uint256 newDateUnfreeze = _freezeTime.add(now);
newDateUnfreeze = (pastDateUnfreeze > newDateUnfreeze ) ? pastDateUnfreeze : newDateUnfreeze;
token.freezeTokens(_beneficiary,totalBloked,newDateUnfreeze);
}
token.mint(_beneficiary,_value);
}
// The function for obtaining smart contract funds in ETH. If all the checks are true, the token is
// transferred to the buyer, taking into account the current bonus.
function buyTokens(address _beneficiary) public payable {
require(_beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 ProfitProcent = getProfitPercent();
uint256 value;
uint256 percent;
uint256 freezeTime;
(value,
percent,
freezeTime) = getBonuses(weiAmount);
Bonus memory curBonus = Bonus(value,percent,freezeTime);
uint256 bonus = curBonus.procent;
// --------------------------------------------------------------------------------------------
// *** Scenario 1 - select max from all bonuses + check maxAllProfit
//uint256 totalProfit = (ProfitProcent < bonus) ? bonus : ProfitProcent;
// *** Scenario 2 - sum both bonuses + check maxAllProfit
uint256 totalProfit = bonus.add(ProfitProcent);
// --------------------------------------------------------------------------------------------
totalProfit = (totalProfit > maxAllProfit) ? maxAllProfit : totalProfit;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate).mul(totalProfit.add(100)).div(100 ether);
// update state
ethWeiRaised = ethWeiRaised.add(weiAmount);
lokedMint(_beneficiary, tokens, curBonus.freezeTime);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
forwardFunds(_beneficiary);//forwardFunds(msg.sender);
}
// buyTokens alias
function () public payable {
buyTokens(msg.sender);
}
}
contract ICreator{
function createAllocation(IToken _token, uint256 _unlockPart1, uint256 _unlockPart2) external returns (IAllocation);
function createFinancialStrategy() external returns(IFinancialStrategy);
function getRightAndRoles() external returns(IRightAndRoles);
}
contract IToken{
function setUnpausedWallet(address _wallet, bool mode) public;
function mint(address _to, uint256 _amount) public returns (bool);
function totalSupply() public view returns (uint256);
function setPause(bool mode) public;
function setMigrationAgent(address _migrationAgent) public;
function migrateAll(address[] _holders) public;
function burn(address _beneficiary, uint256 _value) public;
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount);
function defrostDate(address _beneficiary) public view returns (uint256 Date);
function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public;
}
contract IFinancialStrategy{
enum State { Active, Refunding, Closed }
State public state = State.Active;
event Deposited(address indexed beneficiary, uint256 weiAmount);
event Receive(address indexed beneficiary, uint256 weiAmount);
event Refunded(address indexed beneficiary, uint256 weiAmount);
event Started();
event Closed();
event RefundsEnabled();
function freeCash() view public returns(uint256);
function deposit(address _beneficiary) external payable;
function refund(address _investor) external;
function setup(uint8 _state, bytes32[] _params) external;
function getBeneficiaryCash() external;
function getPartnerCash(uint8 _user, address _msgsender) external;
}
contract IAllocation {
function addShare(address _beneficiary, uint256 _proportion, uint256 _percenForFirstPart) external;
}
contract IRightAndRoles {
address[][] public wallets;
mapping(address => uint16) public roles;
event WalletChanged(address indexed newWallet, address indexed oldWallet, uint8 indexed role);
event CloneChanged(address indexed wallet, uint8 indexed role, bool indexed mod);
function changeWallet(address _wallet, uint8 _role) external;
function setManagerPowerful(bool _mode) external;
function onlyRoles(address _sender, uint16 _roleMask) view external returns(bool);
}
|
Within 400 days (FORCED_REFUND_TIMEOUT1) of the start of the Round, if it fails only investors can take money. After the deadline this can also include the company as well as investors, depending on who is the first to use the method. @ Do I have to use the function no @ When it is possible to call - @ When it is launched automatically - @ Who can call the function beneficiary & manager
|
function distructVault() public {
bytes32[] memory params = new bytes32[](1);
params[0] = bytes32(msg.sender);
if (rightAndRoles.onlyRoles(msg.sender,4) && (now > startTime.add(FORCED_REFUND_TIMEOUT1))) {
financialStrategy.setup(0,params);
}
if (rightAndRoles.onlyRoles(msg.sender,2) && (now > startTime.add(FORCED_REFUND_TIMEOUT2))) {
financialStrategy.setup(0,params);
}
}
| 11,869,855 |
pragma solidity ^0.4.24;
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 addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
function setOwner(address _owner) public onlyOwner {
owner = _owner;
}
function getOwner() public view returns (address) {
return owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
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;
}
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string) {
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 - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool);
}
contract IERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes memory _data
)
public
returns(bytes4);
}
contract IERC721Holder is IERC721Receiver {
function onERC721Received(address, address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory _name);
function symbol() external view returns (string memory _symbol);
function tokenURI(uint256 _tokenId) public view returns (string memory);
}
contract SupportsInterfaceWithLookup is IERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor() public {
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool) {
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract Delegate {
function mint(address _sender, address _to) public returns (bool);
function approve(address _sender, address _to, uint256 _tokenId) public returns (bool);
function setApprovalForAll(address _sender, address _operator, bool _approved) public returns (bool);
function transferFrom(address _sender, address _from, address _to, uint256 _tokenId) public returns (bool);
function safeTransferFrom(address _sender, address _from, address _to, uint256 _tokenId) public returns (bool);
function safeTransferFrom(address _sender, address _from, address _to, uint256 _tokenId, bytes memory _data) public returns (bool);
}
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
{
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
)
public
{
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(
address spender,
uint256 tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param owner owner of the token
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 _addTokenTo(address to, uint256 tokenId) internal {
require(_tokenOwner[tokenId] == address(0));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function _checkAndCallSafeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
}
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256)
{
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
uint256 length = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Reorg all tokens array
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 lastToken = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastToken;
_allTokens[lastTokenIndex] = 0;
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
_allTokensIndex[lastToken] = tokenIndex;
}
}
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string internal _name;
// Token symbol
string internal _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) public {
}
}
contract Collectables is ERC721Full("GU Collectable", "TRINKET"), Ownable {
using Strings for string;
// delegate item specific storage/logic to other contracts
// one main contract manages transfers etc
mapping(uint32 => address) public delegates;
// use uint32s instead of addresses to reduce the storage size needed
// individual token properties should be stored in the delegate contract
uint32[] public collectables;
uint public delegateCount;
event DelegateAdded(address indexed delegate, uint32 indexed delegateID);
function addDelegate(address delegate) public onlyOwner {
uint32 delegateID = uint32(delegateCount++);
// should never happen, but check anyway
require(delegates[delegateID] == address(0), "delegate is already set for collectable type");
delegates[delegateID] = delegate;
emit DelegateAdded(delegate, delegateID);
}
function mint(uint32 delegateID, address to) public returns (uint) {
Delegate delegate = getDelegate(delegateID);
require(delegate.mint(msg.sender, to), "delegate could not mint token");
uint id = collectables.push(delegateID) - 1;
super._mint(to, id);
return id;
}
function transferFrom(address from, address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.transferFrom(msg.sender, from, to, tokenId), "could not transfer token");
super.transferFrom(from, to, tokenId);
}
function approve(address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.approve(msg.sender, to, tokenId), "could not approve token");
super.approve(to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.safeTransferFrom(msg.sender, from, to, tokenId, data), "could not safe transfer token");
super.safeTransferFrom(from, to, tokenId, data);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.safeTransferFrom(msg.sender, from, to, tokenId), "could not safe transfer token");
super.safeTransferFrom(from, to, tokenId);
}
function getTokenDelegate(uint id) public view returns (Delegate) {
address d = delegates[collectables[id]];
require(d != address(0), "invalid delegate");
return Delegate(d);
}
function getDelegate(uint32 id) public view returns (Delegate) {
address d = delegates[id];
require(d != address(0), "invalid delegate");
return Delegate(d);
}
string public constant tokenMetadataBaseURI = "https://api.godsunchained.com/collectable/";
function tokenURI(uint256 _tokenId) public view returns (string memory) {
require(_exists(_tokenId), "token doesn't exist");
return Strings.strConcat(
tokenMetadataBaseURI,
Strings.uint2str(_tokenId)
);
}
}
|
Returns an URI for a given token ID Throws if the token ID does not exist. May return an empty string. tokenId uint256 ID of the token to query/
|
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
| 15,834,551 |
pragma solidity ^0.4.17;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
// additional variables for use if transaction fees ever became necessary
uint public basisPointsRate = 0;
uint public maximumFee = 0;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* @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, uint _value) public onlyPayloadSize(2 * 32) {
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(msg.sender, owner, fee);
}
Transfer(msg.sender, _to, sendAmount);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) public allowed;
uint public constant MAX_UINT = 2**256 - 1;
/**
* @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 uint the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
uint sendAmount = _value.sub(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(_from, owner, fee);
}
Transfer(_from, _to, sendAmount);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded EUROQUINNToken) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract UpgradedStandardToken is StandardToken{
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(address from, address to, uint value) public;
function transferFromByLegacy(address sender, address from, address spender, uint value) public;
function approveByLegacy(address from, address spender, uint value) public;
}
contract EUROQUINNToken is Pausable, StandardToken, BlackList {
string public name;
string public symbol;
uint public decimals;
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
function EUROQUINNToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
_totalSupply = _initialSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[owner] = _initialSupply;
deprecated = false;
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public constant returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
if (deprecated) {
return StandardToken(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public constant returns (uint) {
if (deprecated) {
return StandardToken(upgradedAddress).totalSupply();
} else {
return _totalSupply;
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issuedi
function issue(uint amount) public onlyOwner {
require(_totalSupply + amount > _totalSupply);
require(balances[owner] + amount > balances[owner]);
balances[owner] += amount;
_totalSupply += amount;
Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(_totalSupply >= amount);
require(balances[owner] >= amount);
_totalSupply -= amount;
balances[owner] -= amount;
Redeem(amount);
}
function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
// Ensure transparency by hardcoding limit beyond which fees can never be added
require(newBasisPoints < 20);
require(newMaxFee < 50);
basisPointsRate = newBasisPoints;
maximumFee = newMaxFee.mul(10**decimals);
Params(basisPointsRate, maximumFee);
}
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
// Called if contract ever adds fees
event Params(uint feeBasisPoints, uint maxFee);
}
|
Forward ERC20 methods to upgraded contract if this one is deprecated
|
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
return super.approve(_spender, _value);
}
}
| 436,266 |
./full_match/1/0x053197a8AB5875bF08A05E7524A2fdbe9C4aA59E/sources/project_/contracts/ForeverNft.sol
|
The following functions are overrides required by Solidity.
|
function _beforeTokenTransfer(address from, address to, uint256 tokenId, uint256 batchSize)
internal
override(ERC721, ERC721Snapshot)
{
super._beforeTokenTransfer(from, to, tokenId, batchSize);
}
| 3,006,682 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
interface ICalculateLoan {
function calculateNewDebt(uint principal, uint loanStartDate, uint loanEnd)
external view returns (uint);
function getRate() external view returns (uint);
function adjustRate(uint newRate) external;
}
contract Storage {
struct Borrower {
uint amount; // amount borrowed
uint fromDate; // borrowing date
}
mapping(address => Borrower) balance; // record of all borrowers
address calculatorAddr; // address to library contract (CalculateLoan)
uint outstandingBalance; // amount of credit given
function setCalculatorAddr(address _addr) public payable {
calculatorAddr = _addr;
}
function getRate() public view returns (uint) {
return ICalculateLoan(calculatorAddr).getRate();
}
function issueLoan(address borrower, uint amount) public {
uint currDate = block.timestamp;
balance[borrower] = Borrower(amount, currDate);
// keep track of all our loans
outstandingBalance += amount;
}
// This function can be used by a third party API for a periodic update of debts.
// It is not optimal as of now to have to target each address individually but it
// demonstrates the principle.
function updateBorrower(address borrower) public returns (uint) {
Borrower storage b = balance[borrower];
uint debt = b.amount;
uint fromDate = b.fromDate;
uint actualDate = block.timestamp;
uint newDebt = ICalculateLoan(calculatorAddr).calculateNewDebt(debt, fromDate, actualDate);
if (newDebt > debt) {
balance[borrower].amount = newDebt;
}
}
function getDebtFor(address borrower) public view returns (uint) {
return balance[borrower].amount;
}
function totalCreditGiven() public view returns (uint) {
return outstandingBalance;
}
}
|
keep track of all our loans
|
function issueLoan(address borrower, uint amount) public {
uint currDate = block.timestamp;
balance[borrower] = Borrower(amount, currDate);
outstandingBalance += amount;
}
| 12,638,047 |
/**
*Submitted for verification at Etherscan.io on 2021-05-05
*/
//SPDX-License-Identifier: MIT
pragma solidity 0.7.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library EnumerableMap {
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
MapEntry[] _entries;
mapping (bytes32 => uint256) _indexes;
}
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
map._entries.push(MapEntry({ _key: key, _value: value }));
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
function _remove(Map storage map, bytes32 key) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage);
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
struct UintToAddressMap {
Map _inner;
}
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
library EnumerableSet {
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
library Strings {
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
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) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
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);
}
}
}
}
contract HashGuise {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
mapping(bytes4 => bool) private _supportedInterfaces;
uint256 public constant SALE_START_TIMESTAMP = 1611846000;
uint256 public constant MAX_NFT_SUPPLY = 100;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Keeps track of how much each index was minted for
mapping (uint8 => uint256) public mintedPrice;
// Token symbol
string private _symbol;
string private _name;
uint256 public mintedCounter;
uint256 public colorCounter;
uint8 [] public availableNFTs;
address public _owner;
bool public readyForSale;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
constructor () {
_name = "HashGuise";
_symbol = "HSGS";
_owner = msg.sender;
bytes4 _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 _INTERFACE_ID_ERC721_METADATA = 0x93254542;
bytes4 _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
_supportedInterfaces[_INTERFACE_ID_ERC165] = true;
_supportedInterfaces[_INTERFACE_ID_ERC721] = true;
_supportedInterfaces[_INTERFACE_ID_ERC721_METADATA] = true;
_supportedInterfaces[_INTERFACE_ID_ERC721_ENUMERABLE] = true;
// 0 ... 99 tokenIDs available to purchase
// 100 ... 199 tokenIDs for color that mirror their bw 0 ... 99 IDs
for(uint8 _index; _index < 100; _index++)
availableNFTs.push(_index);
}
function supportsInterface(bytes4 interfaceId) public view returns (bool) {
return _supportedInterfaces[interfaceId];
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
function ownerOf(uint256 tokenId) public view returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
return _holderTokens[owner].at(index);
}
function totalSupply() public view returns (uint256) {
return _tokenOwners.length();
}
function tokenByIndex(uint256 index) public view returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
function distributionCurve(bool _forColor) public view returns (uint256) {
uint256 _counter = _forColor == true ? colorCounter : mintedCounter;
uint256 weiAmount = 0;
if(_forColor == true){
weiAmount = 50e16;
} else if(_counter < 2){
weiAmount = 10e16;
} else if(_counter < 5){
weiAmount = 23e16;
} else if(_counter < 10){
weiAmount = 45e16;
} else if(_counter < 15){
weiAmount = 68e16;
} else if(_counter < 20){
weiAmount = 90e16;
} else if(_counter < 25){
weiAmount = 113e16;
} else if(_counter < 30){
weiAmount = 135e16;
} else if(_counter < 35){
weiAmount = 158e16;
} else if(_counter < 40){
weiAmount = 180e16;
} else if(_counter < 45){
weiAmount = 203e16;
} else if(_counter < 50){
weiAmount = 225e16;
} else if(_counter < 55){
weiAmount = 248e16;
} else if(_counter < 60){
weiAmount = 270e16;
} else if(_counter < 65){
weiAmount = 293e16;
} else if(_counter < 70){
weiAmount = 317e16;
} else if(_counter < 75){
weiAmount = 342e16;
} else if(_counter < 80){
weiAmount = 373e16;
} else if(_counter < 85){
weiAmount = 416e16;
} else if(_counter < 90){
weiAmount = 497e16;
} else if(_counter < 95){
weiAmount = 675e16;
} else if(_counter < 100){
weiAmount = 1118e16;
}
return weiAmount;
}
function changeToColor(uint256[] calldata index) external payable {
require(readyForSale == true, "HashGuise::changeToColor: not ready for sale");
require(index.length > 0);
uint256 returnAmount = msg.value;
for(uint _index = 0; _index < index.length; _index++){
uint256 requiredWei = distributionCurve(true);
if(returnAmount < requiredWei)
break;
require(returnAmount >= requiredWei, "HashGuise::changeToColor: not enough ETH");
require(index[_index] < 100, "HashGuise::changeToColor: already color");
require(ownerOf(index[_index]) == msg.sender, "HashGuise::changeToColor: not the owner");
uint256 colorIndex = index[_index].add(100);
returnAmount = returnAmount.sub(requiredWei);
_burn(index[_index]);
_safeMint(msg.sender, colorIndex);
colorCounter++;
}
// refund any excess eth
if(returnAmount > 0){
(bool success, ) = address(msg.sender).call{ value: returnAmount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
function mintNFT() public payable {
require(readyForSale == true, "HashGuise::changeToColor: not ready for sale");
uint256 mintPrice = distributionCurve(false);
require(mintPrice != 0, "HashGuise::mintNFT: Sale has already ended");
require(mintPrice <= msg.value, "HashGuise::mintNFT: Ether value sent is not correct");
uint256 returnAmount = msg.value;
while (returnAmount >= mintPrice && mintPrice != 0){
returnAmount = returnAmount.sub(mintPrice);
uint256 randomMintIndex = uint(blockhash(block.number - 1)) % (availableNFTs.length);
if(availableNFTs.length == 1)
randomMintIndex = 0;
mintedPrice[uint8(randomMintIndex)] = mintPrice;
_safeMint(msg.sender, availableNFTs[randomMintIndex]);
// reorder array, creates more randomness
if(randomMintIndex != availableNFTs.length.sub(1)){
availableNFTs[randomMintIndex] = availableNFTs[availableNFTs.length.sub(1)];
}
delete availableNFTs[availableNFTs.length.sub(1)];
availableNFTs.pop();
mintedCounter++;
}
// refund any excess eth
if(returnAmount > 0){
(bool success, ) = address(msg.sender).call{ value: returnAmount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
function withdraw() public {
require(msg.sender == _owner, "Not the owner");
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function setReadyForSale(bool _readyForSale) public {
require(msg.sender == _owner, "Not the owner");
readyForSale = _readyForSale;
}
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, ""), "ERC721: transfer to non ERC721Receiver implementer");
}
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal {
address owner = ownerOf(tokenId);
// Clear approvals
_approve(address(0), tokenId);
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
msg.sender,
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
}
interface IERC20 {
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function burn(uint256 burnQuantity) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC721Receiver {
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
|
reorder array, creates more randomness refund any excess eth
|
function mintNFT() public payable {
require(readyForSale == true, "HashGuise::changeToColor: not ready for sale");
uint256 mintPrice = distributionCurve(false);
require(mintPrice != 0, "HashGuise::mintNFT: Sale has already ended");
require(mintPrice <= msg.value, "HashGuise::mintNFT: Ether value sent is not correct");
uint256 returnAmount = msg.value;
while (returnAmount >= mintPrice && mintPrice != 0){
returnAmount = returnAmount.sub(mintPrice);
uint256 randomMintIndex = uint(blockhash(block.number - 1)) % (availableNFTs.length);
if(availableNFTs.length == 1)
randomMintIndex = 0;
mintedPrice[uint8(randomMintIndex)] = mintPrice;
_safeMint(msg.sender, availableNFTs[randomMintIndex]);
if(randomMintIndex != availableNFTs.length.sub(1)){
availableNFTs[randomMintIndex] = availableNFTs[availableNFTs.length.sub(1)];
}
delete availableNFTs[availableNFTs.length.sub(1)];
availableNFTs.pop();
mintedCounter++;
}
if(returnAmount > 0){
require(success, "Address: unable to send value, recipient may have reverted");
}
}
| 2,147,349 |
pragma solidity ^0.4.11;
contract ChronoBankPlatform {
mapping(bytes32 => address) public proxies;
function symbols(uint _idx) public constant returns (bytes32);
function symbolsCount() public constant returns (uint);
function name(bytes32 _symbol) returns(string);
function setProxy(address _address, bytes32 _symbol) returns(uint errorCode);
function isCreated(bytes32 _symbol) constant returns(bool);
function isOwner(address _owner, bytes32 _symbol) returns(bool);
function owner(bytes32 _symbol) constant returns(address);
function totalSupply(bytes32 _symbol) returns(uint);
function balanceOf(address _holder, bytes32 _symbol) returns(uint);
function allowance(address _from, address _spender, bytes32 _symbol) returns(uint);
function baseUnit(bytes32 _symbol) returns(uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) returns(uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) returns(uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) returns(uint errorCode);
function isReissuable(bytes32 _symbol) returns(bool);
function changeOwnership(bytes32 _symbol, address _newOwner) returns(uint errorCode);
}
contract ChronoBankAsset {
function __transferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function __approve(address _spender, uint _value, address _sender) returns(bool);
function __process(bytes _data, address _sender) payable {
revert();
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
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);
}
/**
* @title ChronoBank Asset Proxy.
*
* Proxy implements ERC20 interface and acts as a gateway to a single platform asset.
* Proxy adds symbol and caller(sender) when forwarding requests to platform.
* Every request that is made by caller first sent to the specific asset implementation
* contract, which then calls back to be forwarded onto platform.
*
* Calls flow: Caller ->
* Proxy.func(...) ->
* Asset.__func(..., Caller.address) ->
* Proxy.__func(..., Caller.address) ->
* Platform.proxyFunc(..., symbol, Caller.address)
*
* Asset implementation contract is mutable, but each user have an option to stick with
* old implementation, through explicit decision made in timely manner, if he doesn't agree
* with new rules.
* Each user have a possibility to upgrade to latest asset contract implementation, without the
* possibility to rollback.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract ChronoBankAssetProxy is ERC20 {
// Supports ChronoBankPlatform ability to return error codes from methods
uint constant OK = 1;
// Assigned platform, immutable.
ChronoBankPlatform public chronoBankPlatform;
// Assigned symbol, immutable.
bytes32 public smbl;
// Assigned name, immutable.
string public name;
string public symbol;
/**
* Sets platform address, assigns symbol and name.
*
* Can be set only once.
*
* @param _chronoBankPlatform platform contract address.
* @param _symbol assigned symbol.
* @param _name assigned name.
*
* @return success.
*/
function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) returns(bool) {
if (address(chronoBankPlatform) != 0x0) {
return false;
}
chronoBankPlatform = _chronoBankPlatform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
function stringToBytes32(string memory source) returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
/**
* Only platform is allowed to call.
*/
modifier onlyChronoBankPlatform() {
if (msg.sender == address(chronoBankPlatform)) {
_;
}
}
/**
* Only current asset owner is allowed to call.
*/
modifier onlyAssetOwner() {
if (chronoBankPlatform.isOwner(msg.sender, smbl)) {
_;
}
}
/**
* Returns asset implementation contract for current caller.
*
* @return asset implementation contract.
*/
function _getAsset() internal returns(ChronoBankAsset) {
return ChronoBankAsset(getVersionFor(msg.sender));
}
/**
* Returns asset total supply.
*
* @return asset total supply.
*/
function totalSupply() constant returns(uint) {
return chronoBankPlatform.totalSupply(smbl);
}
/**
* Returns asset balance for a particular holder.
*
* @param _owner holder address.
*
* @return holder balance.
*/
function balanceOf(address _owner) constant returns(uint) {
return chronoBankPlatform.balanceOf(_owner, smbl);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender) constant returns(uint) {
return chronoBankPlatform.allowance(_from, _spender, smbl);
}
/**
* Returns asset decimals.
*
* @return asset decimals.
*/
function decimals() constant returns(uint8) {
return chronoBankPlatform.baseUnit(smbl);
}
/**
* Transfers asset balance from the caller to specified receiver.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transfer(address _to, uint _value) returns(bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
/**
* Transfers asset balance from the caller to specified receiver adding specified comment.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
*
* @return success.
*/
function transferWithReference(address _to, uint _value, string _reference) returns(bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
/**
* Resolves asset implementation contract for the caller and forwards there arguments along with
* the caller address.
*
* @return success.
*/
function _transferWithReference(address _to, uint _value, string _reference) internal returns(bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
/**
* Performs transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) {
return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
/**
* Prforms allowance transfer of asset balance between holders.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transferFrom(address _from, address _to, uint _value) returns(bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) {
return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
*
* @return success.
*/
function approve(address _spender, uint _value) returns(bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance setting call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _sender initial caller.
*
* @return success.
*/
function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) returns(bool) {
return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
/**
* Emits ERC20 Transfer event on this contract.
*
* Can only be, and, called by assigned platform when asset transfer happens.
*/
function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform() {
Transfer(_from, _to, _value);
}
/**
* Emits ERC20 Approval event on this contract.
*
* Can only be, and, called by assigned platform when asset allowance set happens.
*/
function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform() {
Approval(_from, _spender, _value);
}
/**
* Resolves asset implementation contract for the caller and forwards there transaction data,
* along with the value. This allows for proxy interface growth.
*/
function () payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
/**
* Indicates an upgrade freeze-time start, and the next asset implementation contract.
*/
event UpgradeProposal(address newVersion);
// Current asset implementation contract address.
address latestVersion;
// Proposed next asset implementation contract address.
address pendingVersion;
// Upgrade freeze-time start.
uint pendingVersionTimestamp;
// Timespan for users to review the new implementation and make decision.
uint constant UPGRADE_FREEZE_TIME = 3 days;
// Asset implementation contract address that user decided to stick with.
// 0x0 means that user uses latest version.
mapping(address => address) userOptOutVersion;
/**
* Only asset implementation contract assigned to sender is allowed to call.
*/
modifier onlyAccess(address _sender) {
if (getVersionFor(_sender) == msg.sender) {
_;
}
}
/**
* Returns asset implementation contract address assigned to sender.
*
* @param _sender sender address.
*
* @return asset implementation contract address.
*/
function getVersionFor(address _sender) constant returns(address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
/**
* Returns current asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getLatestVersion() constant returns(address) {
return latestVersion;
}
/**
* Returns proposed next asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getPendingVersion() constant returns(address) {
return pendingVersion;
}
/**
* Returns upgrade freeze-time start.
*
* @return freeze-time start.
*/
function getPendingVersionTimestamp() constant returns(uint) {
return pendingVersionTimestamp;
}
/**
* Propose next asset implementation contract address.
*
* Can only be called by current asset owner.
*
* Note: freeze-time should not be applied for the initial setup.
*
* @param _newVersion asset implementation contract address.
*
* @return success.
*/
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {
// Should not already be in the upgrading process.
if (pendingVersion != 0x0) {
return false;
}
// New version address should be other than 0x0.
if (_newVersion == 0x0) {
return false;
}
// Don't apply freeze-time for the initial setup.
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposal(_newVersion);
return true;
}
/**
* Cancel the pending upgrade process.
*
* Can only be called by current asset owner.
*
* @return success.
*/
function purgeUpgrade() onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
/**
* Finalize an upgrade process setting new asset implementation contract address.
*
* Can only be called after an upgrade freeze-time.
*
* @return success.
*/
function commitUpgrade() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
/**
* Disagree with proposed upgrade, and stick with current asset implementation
* until further explicit agreement to upgrade.
*
* @return success.
*/
function optOut() returns(bool) {
if (userOptOutVersion[msg.sender] != 0x0) {
return false;
}
userOptOutVersion[msg.sender] = latestVersion;
return true;
}
/**
* Implicitly agree to upgrade to current and future asset implementation upgrades,
* until further explicit disagreement.
*
* @return success.
*/
function optIn() returns(bool) {
delete userOptOutVersion[msg.sender];
return true;
}
}
|
Transfers asset balance from the caller to specified receiver. _to holder address to give to. _value amount to transfer. return success./
|
function transfer(address _to, uint _value) returns(bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
| 15,415,238 |
/*
NumberBetManager
v 1.0.0
http://www.get242.com/numberbet
Copyright © 2019 S.H. LEE <[email protected]>
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar. See the COPYING file for more details.
*/
pragma solidity ^0.5.6;
/// @title Basic operational actions
/// @notice You can use this contract for the basic simulation
/// @dev All function calls are currently implemented without side effects
contract OperationalControl {
// Holds a position of authority to execute operational actions
address payable public operator;
// If true, major operational actions are blocked
bool public isPaused;
/// @dev Emited when contract variable is changed
event OptionChanged(address operator);
/// @dev Operation modifiers for restricted access
modifier onlyOperator() {
require(msg.sender == operator);
_;
}
/// @dev Change operator address by previous operator
function changeOperator(address payable _newOperator) public onlyOperator {
operator = _newOperator;
emit OptionChanged(msg.sender);
}
/// @dev Stops the availability of contract actions
function pauseContract() public onlyOperator {
isPaused = true;
emit OptionChanged(msg.sender);
}
/// @dev Resumes the availability of contract actions
function unpauseContract() public onlyOperator {
isPaused = false;
emit OptionChanged(msg.sender);
}
/// @notice Any kinds of donation is welcome
function() external payable {}
/// @dev Pleasure of mine
function withdraw(uint256 _amount) public onlyOperator {
require(address(this).balance >= _amount);
operator.transfer(_amount);
emit OptionChanged(msg.sender);
}
/// @dev Just in case
function kill() public onlyOperator {
selfdestruct(operator);
}
}
/*
ORACLIZE_API
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
contract usingOraclize {
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 - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d,
string memory _e
) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
}
/// @title A managing contract for guessing number bet
/// @notice Make and take bet for transfering the ownership
/// @dev All function calls are currently implemented without side effects
contract NumberBetManager is OperationalControl, usingOraclize {
// Maximum number of table
uint256 public maxTable;
// Maximum number of case
uint256 public maxCase;
/// @dev In percentage
uint256 public feeRate;
/// @dev Table index with bet maker's and taker's information
struct Table {
// Address of the maker
address payable maker;
// Deposit of the bet which can be lost by losing bet
uint256 deposit;
// Hashed number given by the maker
bytes32 hashedNum;
// Allowed time for maker to show real number not to lose his deposit
// This value is given by maker and long duration costs higher fee
uint256 allowedTime;
// Address of the taker
address payable taker;
// Taker's payment
uint256 payment;
// Guessed number given by the taker
uint256 guessedNum;
// The time that taker takes
uint256 takingTime;
}
/// @notice House has many tables
/// @dev Table index with maker and taker informations
mapping (uint256 => Table) public tables;
/// @dev Emited when table variable is changed
event TableChanged(uint256 tableIndex);
/// @dev Emited when contract sends eth out
event SendEth(address payable sendTo, uint256 amountTo);
/// @dev Comparison result event for verification purpose
event revealNum(bytes32 hashedNum, string realNumStr, string strToHash, bytes32 realHashedNum);
/// @dev Manager receives fee in some cases
event receiveFee(uint256 amount);
/// @dev Creates a reference to GachaTicket contract
constructor(uint256 _maxTable, uint256 _maxCase, uint256 _feeRate) public {
// OperationalControl
operator = msg.sender;
isPaused = false;
// NumberBetManager
maxTable = _maxTable;
maxCase = _maxCase;
feeRate = _feeRate;
}
/// @notice Maker can maker the bet by paying deposit
/// @dev Maker's information is added to the struct
/// @param _tableIndex Shows the table position
/// @param _hashedNum Hash(sha256): Number + salt
/// @param _allowedTime In seconds
function makeBet(
uint256 _tableIndex,
bytes32 _hashedNum,
uint256 _allowedTime
) public payable {
// Check that contract is not paused
require(!isPaused);
// Check table index is less than maximum number
require(_tableIndex < maxTable);
// Check that selected table is available for making a bet
require(tables[_tableIndex].maker == address(0) && tables[_tableIndex].taker == address(0));
// Requires minimum bet of 0.001 ETH
require(msg.value >= 1000000000000000);
// Exact amount is nedded for taker's to pay
require(msg.value % maxCase == 0);
// Minumum waiting of 2 min and maximum of 1 hr for taker to unearn the bet
require(120 <= _allowedTime && _allowedTime <= 3600);
Table storage table = tables[_tableIndex];
table.maker = msg.sender;
table.deposit = msg.value;
table.hashedNum = _hashedNum;
table.allowedTime = _allowedTime;
emit TableChanged(_tableIndex);
}
/// @notice Taker can join the bet by paying specified amount
/// @dev Taker's information is added to the struct
/// @param _tableIndex Shows the table position
/// @param _guessedNum Taker's guessed number to the maker's real number
function takeBet(
uint256 _tableIndex,
uint256 _guessedNum
) public payable {
// Check that contract is not paused
require(!isPaused);
// Check table index is less than maximum number
require(_tableIndex < maxTable);
// Check that selected table is available for making a bet
require(tables[_tableIndex].maker != address(0) && tables[_tableIndex].taker == address(0));
// Check that taker pays properly
require(tables[_tableIndex].deposit == msg.value * maxCase);
Table storage table = tables[_tableIndex];
table.taker = msg.sender;
table.payment = msg.value;
table.guessedNum = _guessedNum;
table.takingTime = now;
emit TableChanged(_tableIndex);
}
/// @notice Maker can finalize the bet by submitting the real number
/// @dev Verifies maker's submitted number by hashing
/// @param _tableIndex Shows the table position
/// @param _realNum Taker's real number
/// @param _saltWord Salt word to hash the real number
function finalizeBet(
uint256 _tableIndex,
uint256 _realNum,
string memory _saltWord
) public {
// Check that contract is not paused
require(!isPaused);
// Check table index is less than maximum number
require(_tableIndex < maxTable);
// Maker can only send real number
require(msg.sender == tables[_tableIndex].maker);
// Check that selected table is available for making a bet
require(tables[_tableIndex].maker != address(0) && tables[_tableIndex].taker != address(0));
// Check table index is less than maximum number
require(_realNum < maxCase);
string memory realNumStr = uint2str(_realNum);
string memory strToHash = strConcat(realNumStr, _saltWord);
bytes32 realHashedNum = sha256(bytes(strToHash));
emit revealNum(tables[_tableIndex].hashedNum, realNumStr, strToHash, realHashedNum);
// Verify submitted real number is same as previously submitted hashed number
//hashedNum = crypto.createHash(‘sha256’).update(Num + Salt).digest(‘hex’)
require(tables[_tableIndex].hashedNum == realHashedNum);
if (_realNum == tables[_tableIndex].guessedNum) {
// Case: taker win (taker guessed it right)
address payable addressToSend = tables[_tableIndex].taker;
uint256 amountToSend = tables[_tableIndex].deposit;
address payable addressToRefund = tables[_tableIndex].maker;
uint256 amountToRefund = tables[_tableIndex].payment;
delete tables[_tableIndex];
emit SendEth(addressToSend, amountToSend);
addressToSend.transfer(amountToSend);
emit SendEth(addressToRefund, amountToRefund);
addressToRefund.transfer(amountToRefund);
} else {
// Case: maker win
address payable addressToSend = tables[_tableIndex].maker;
uint256 amountToSend = tables[_tableIndex].deposit + tables[_tableIndex].payment;
delete tables[_tableIndex];
emit SendEth(addressToSend, amountToSend);
addressToSend.transfer(amountToSend);
}
emit TableChanged(_tableIndex);
}
/// @notice Taker can redeem the bet regardless of maker's appearance but it cost
/// @dev Taker can only redeem the bet after a period of time set by maker
/// @param _tableIndex Shows the table position
function unearnedBet(uint256 _tableIndex) public {
// Check that contract is not paused
require(!isPaused);
// Check table index is less than maximum number
require(_tableIndex < maxTable);
// Taker can only execute this function
require(msg.sender == tables[_tableIndex].taker);
// Check that selected table is available for making a bet
require(tables[_tableIndex].maker != address(0) && tables[_tableIndex].taker != address(0));
// Check that taker pays properly
require(now > tables[_tableIndex].takingTime + tables[_tableIndex].allowedTime);
address payable addressToSend = tables[_tableIndex].taker;
uint256 feeToManager = tables[_tableIndex].deposit * feeRate / 100;
uint256 amountToSend = tables[_tableIndex].deposit - feeToManager;
address payable addressToRefund = tables[_tableIndex].maker;
uint256 amountToRefund = tables[_tableIndex].payment;
delete tables[_tableIndex];
emit receiveFee(feeToManager);
emit SendEth(addressToSend, amountToSend);
addressToSend.transfer(amountToSend);
emit SendEth(addressToRefund, amountToRefund);
addressToRefund.transfer(amountToRefund);
emit TableChanged(_tableIndex);
}
/// @notice Maker can cancel the bet if there is no taker
/// @dev Resets the table status permanently
/// @param _tableIndex Shows the table position
function cancelBet(uint256 _tableIndex) public {
// Check that contract is not paused
require(!isPaused);
// Check table index is less than maximum number
require(_tableIndex < maxTable);
// Maker can only send real number
require(msg.sender == tables[_tableIndex].maker);
// Check that selected table is available for canceling a bet
require(tables[_tableIndex].taker == address(0));
address payable makerAddress = tables[_tableIndex].maker;
uint256 makerAmount = tables[_tableIndex].deposit;
delete tables[_tableIndex];
emit SendEth(makerAddress, makerAmount);
makerAddress.transfer(makerAmount);
emit TableChanged(_tableIndex);
}
/// @notice In case table is stucked by anonymous reason
/// @dev Resets the table status permanently
/// @param _tableIndex Shows the table position
function resetTable(uint256 _tableIndex) public onlyOperator {
// Check that contract is paused
require(isPaused);
address payable makerAddress = tables[_tableIndex].maker;
uint256 makerAmount = tables[_tableIndex].deposit;
address payable takerAddress = tables[_tableIndex].taker;
uint256 takerAmount = tables[_tableIndex].payment;
delete tables[_tableIndex];
if (makerAmount != 0) {
emit SendEth(makerAddress, makerAmount);
makerAddress.transfer(makerAmount);
}
if (takerAmount != 0) {
emit SendEth(takerAddress, takerAmount);
takerAddress.transfer(takerAmount);
}
emit TableChanged(_tableIndex);
}
/// @dev Changes maximum number of tables
function changeMaxTable(uint256 _maxTable) public onlyOperator {
// Check that contract is paused
require(isPaused);
maxTable = _maxTable;
emit OptionChanged(msg.sender);
}
/// @dev Changes maximum number of cases
function changeMaxCase(uint256 _maxCase) public onlyOperator {
// Check that contract is paused
require(isPaused);
maxCase = _maxCase;
emit OptionChanged(msg.sender);
}
/// @dev Changes fee rate in percentage
function changeFeeRate(uint256 _feeRate) public onlyOperator {
// Check that contract is paused
require(isPaused);
feeRate = _feeRate;
emit OptionChanged(msg.sender);
}
function getCurrentEth() public view returns (uint256 _balance) {
return address(this).balance;
}
}
|
Changes maximum number of tables Check that contract is paused
|
function changeMaxTable(uint256 _maxTable) public onlyOperator {
require(isPaused);
maxTable = _maxTable;
emit OptionChanged(msg.sender);
}
| 6,428,921 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.